scala - Anonymous function as parameter -


def fun(f: int => unit) {   f(10)   f(20) } println("method 1 call:") fun(i => {println("hi"); println(i)}) println("method 2 call:") fun{println("hi"); println(_)} 

the output is:

e:\test\scala>scala i.scala method 1 call: hi 10 hi 20 method 2 call: hi 10 20 

i think i => {println("hi"); println(i)} , println("hi"); println(_) same. because have 1 parameter , parameter used once, can use _ simplify code.

then, why method 2 print "hi" once? (does mean: if want use _ simple calling, contents on right of => can have 1 expression, if have more one, e.g. println("hi"); println(i); then, can not use _ replace?

first, have know in scala { block; of; code } expression evaluates whatever last expression inside evaluates to.

when say:

fun(i => { println("hi"); println(i) }) 

you create anonymous function, body contains 2 expressions, both returning () , both evaluated when function called, expected.

but when say

fun({println("hi"); println(_)}) 

you pass in block, not anonymous function. sepp2k explained expands to

{ println("hi"); x => println(x) } 

so, pass block fun, block being evaluated before passed. first println("hi") happens, printed once block evaluated once, , x => println(x) evaluated, function int => unit, prints argument. this, , (as last expression passed fun. why each time call fun prints argument twice.

to see further on how block work can @ example more in block

fun {   println("building function")   val uuidofthisfunction = uuid.randomuuid   x => println(s"$uuidofthisfunction, $x") } 

so block prepares function giving context through closure. uuid stay same both calls happen if fun.

building function 86e74b5e-83b5-41f3-a71c-eeafcd1db2a0, 10 86e74b5e-83b5-41f3-a71c-eeafcd1db2a0, 20 

the example more did first call be

fun(   x => {     println("calling function")     val uuidofthiscall = uuid.randomuuid     println(s"$uuidofthiscall, $x")   } ) 

the block evaluates every time f called.

calling function d3c9ff0a-84b4-47a3-8153-c002fa16d6c2, 10 calling function a0b1aa5b-c0ea-4047-858b-9db3d43d4983, 20 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -