[英]Scala function evaluation
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 ? 为什么在函数foreach2中未调用函数f1?
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". 函数f1似乎在foreach2之前得到了评估,因为在“ foreach2”之前打印了“ f here”。 Why is this the case ? 为什么会这样呢?
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
. 因为您没有调用它,所以要返回它,因此foreach2
函数的推断结果类型将为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. 在第二种情况下,有一个特殊的规则适用,您可以不带花括号地调用f1
函数(不带参数),因此基本上是将f1
调用的结果(不带花括号)绑定到您的foreach2
函数的f
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.