Reputation: 7526
In following code:
scala> val double = (i: Int) => {
| println("I am here")
| i * 2
| }
double: Int => Int = $$Lambda$1090/773348080@6ae9b2f0
scala> double(4)
I am here
res22: Int = 8
scala> val evenFunc: (Int => Boolean) = {
| println("I am here");
| (x => x % 2 == 0)
| }
I am here
evenFunc: Int => Boolean = $$Lambda$1091/373581540@a7c489a
scala> double
res23: Int => Int = $$Lambda$1090/773348080@6ae9b2f0
scala> evenFunc
res24: Int => Boolean = $$Lambda$1091/373581540@a7c489a
scala> evenFunc(10)
res25: Boolean = true
scala> def incr(x:Int) = x+1
incr: (x: Int)Int
scala> incr
<console>:13: error: missing argument list for method incr
Unapplied methods are only converted to functions when a function type is
expected.
You can make this conversion explicit by writing `incr _` or `incr(_)`
instead of `incr`.
incr
double and evenFunc are function variables and we have assigned function literals to them.But as output shows, when we call double, println statement is also executed.But evenFunc doesn't execute println statement, except when defined. incr is defined with keyword def, so its behaviour is as expected.
Why do double and evenFunc behave differently, even though both refer to function literals?
Upvotes: 1
Views: 291
Reputation: 850
The difference is rather clear
(i: Int) => {
println("I am here")
i * 2
}
{
println("I am here");
(x => x % 2 == 0)
}
The function literal is defined as (param list) => body
. Hence, the println
statement in the 2nd is evaluated before and beyond the the function literal so that it's not part of the function body.
Upvotes: 2
Reputation: 51271
The point at which the input parameter is received is the pivot.
If you change evenFunc
from...
println("I am here")
x => x % 2 == 0
... to ...
x =>
println("I am here")
x % 2 == 0
...you'll get the same behavior as observed with double
.
What comes before the received argument is evaluated/executed where the function is defined. What comes after the received argument is executed each time the function is invoked.
Upvotes: 3