Scala lambda function not allowed on parameter type declaration?

when defining a 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 is not working? Is there any ambiguity in it?

+3


source to share


2 answers


One possible explanation is that this limitation avoids ambiguity: x: A => B

it can be thought of as an anonymous function that takes a x

type parameter A

and returns an object B

. Or, it can be understood as "casting" a variable x

to a type A => B

. It is very rare that both are 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

      

+2


source


All of these options are covered in the Anonymous Functions section of the specification . Relevant part

In the case of one untyped formal parameter, it (x) => e

 can be abbreviated to x => e

. If an anonymous function (x : T) => e

 with one typed parameter appears as the result of a block expression, it can be abbreviated to x: T => e

.



The method3

function is not a block result expression; into method4

this.

EDIT: oops, apparently you meant why the limitation exists. I'll leave this answer for the moment stating what the constraint is and remove it if anyone gives a better answer.

0


source







All Articles