Reputation: 53826
In below code :
object typeparam {
val v = new MyClass[Int] //> v : typeparam.MyClass[Int] = typeparam$MyClass@17943a4
def f1(a : Int) = {
println("f here")
3
} //> f1: (a: Int)Int
v.foreach2(f1) //> foreach2
class MyClass[A] {
def foreach2[B](f: B => A) = {
println("foreach2")
f
}
}
}
Why is function f1 not invoked within function foreach2 ?
If I instead use
object typeparam {
val v = new MyClass[Int] //> v : typeparam.MyClass[Int] = typeparam$MyClass@14fe5c
def f1() = {
println("f here")
} //> f1: ()Unit
v.foreach2(f1) //> f here
//| foreach2
class MyClass[A] {
def foreach2[B](f: Unit) = {
println("foreach2")
f
}
}
}
The function f1 appears to get evaluated before foreach2 , as "f here" is printed before "foreach2". Why is this the case ?
Upvotes: 0
Views: 212
Reputation: 21557
Because you are not invoking it, you are returning it as a result, the inferred result type of your foreach2
function would be Int => Int
. You need to invoke this function with some argument. In the second case a special rules applies, you can invoke function like f1
(which doesn't take arguments) without braces, so basically you are binding a result of f1
invocation (without braces) to the f
parameter of your foreach2
function.
Upvotes: 3