Reputation: 465
I have the next code, where I study call by name.
def callByName(v1: => Int) ={
println(v1)
println(v1)
}
val fn1 : (Int => Int) = {println("calling fn1 "); _ + 100}
callByName(fn1(1))
println("=================")
val fn2 = (x: Int) => {println("calling fn2 "); x + 100 }
callByName(fn2(1))
I expect the same output, but it is:
calling fn1
fn1: Int => Int = <function>89c5c0
101
101
=================
fn2: Int => Int = <function>d15e781
calling fn2
101
calling fn2
101
I know that the second case is a "function literal (also known as an anonymous function)".
Could you tell me please where I can read about these 2 cases or explain? Thanks.
And the third case:
val fn1 : (Int => Int) = {println("calling fn1 "); _ + 100}
println(fn1(1))
println(fn1(2))
println(fn1(3))
Output:
calling fn1
fn1: Int => Int = <function>da62626
101
102
103
In this last case "body of the function executed 3 times", but only last part "_ + 100" and the first part only 1 time "println("calling fn1 ");"
Huh.
Upvotes: 2
Views: 53
Reputation: 13985
Well... So your first case is bit weird and causing some confusion to you.
So, your first case,
val fn1 : (Int => Int) = {
println("calling fn1 ")
_ + 100
}
is actually,
val fn1 : (Int => Int) = {
println("calling fn1 ")
val xx: Int => Int = _ + 100
xx
}
It is similar to,
val i: Int = {
println("creating int")
5
}
So, your fn1
is just that xx
. It has no relation with println("calling fn1 ")
line.
Where as in your second case println("calling fn2 ")
is also part of fn2
.
Upvotes: 1