scala - Confused about function literals -
scala newbie here.
i have set defined , declared follows:
var g = set(1,2,3)
now want print out each element of set follows using function literal:
scala> g.foreach(s => println(s)) 1 2 3
all good.
i can more concise this:
scala> g.foreach(println) 1 2 3
all good.
now when this:
scala> g.foreach(println()) <console>:9: error: type mismatch; found : unit required: int => ? g.foreach(println())
why fail? me (a newbie), seems equivalent of g.foreach(println)
. please can explain error.
when pass function literal or function directly, in first 2 examples, do not invoke function immediately. however, in last example do invoke it, because println()
syntax calling functions , methods. because println()
result type unit
, you're in fact passing value of type unit
method expects value of type (string) => unit
, , of course these different values, compiler shows error.
Comments
Post a Comment