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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -