Search code examples
scalalambdacompiler-construction

Scala lambda function not resolved when declares the type of parameter?


when defining method in Scala, I found this

def method1: Int => Int = (j: Int) => j  // works
def method2: Int => Int = j => j  // works
def method3: Int => Int = j: Int => j  // error
def method4: Int => Int = {j: Int => j}  // works

Can anyone explain why method3 does not work? Is there any ambiguity in it?


Solution

  • One possible explanation is indeed that this restriction avoids ambiguity: x: A => B could be understood as an anonymous function that takes a parameter x of type A and returns the object B. Or it could be understood as "casting" a variable x to the type A => B. It is very rare that both of these would be valid programs, but not impossible. Consider:

    class Foo(val n: Int)
    val Foo = new Foo(0)
    val j: Int => Foo = new Foo(_)
    
    def method1: Int => Foo = (j: Int) => Foo
    def method2: Int => Foo = j: Int => Foo
    
    println(method1(1).n)
    println(method2(1).n)
    

    This actually compiles and prints:

    0
    1