Scala lambda function not resolved when declares the type of parameter? -
when defining method in scala, 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 explain why method3 not work? there ambiguity in it?
one possible explanation indeed restriction avoids ambiguity: x: => b
understood anonymous function takes parameter x
of type a
, returns object b
. or understood "casting" variable x
type a => b
. rare both of these valid programs, 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 compiles , prints:
0 1
Comments
Post a Comment