在下面的代码示例中,我不明白为什么fun函数可以作为参数传递给方法addAction
。方法fun
的类型为Unit
,而方法addAction
预计类型为() => Unit
的函数。Scala方法类型和方法作为参数
如果fun
是() => Unit
型的,那么,为什么编译器抱怨fun
是Unit
类型的,当我尝试添加fun
到操作列表:actions = fun :: actions
?
package myscala
object MyScala {
def fun() { println("fun1 executed.") }
def addAction(a:() => Unit) {
actions = a :: actions
}
var actions: List[() => Unit] = List()
def main(args: Array[String]) {
// the following line would produce a compiler error (found: Unit, required:() => Unit), it's OK
// actions = fun :: actions
actions = (() => fun) :: actions // OK
// I would expect the same compiler error here (found: Unit, required:() => Unit), but it's OK why?
addAction(fun)
actions.foreach(_()) // prints twice "fun1 executed"
}
}
是的,我愿意。这对我来说现在看起来很明显(当时根本没有)。当编译器能够推断出一个函数类型的时候,我可以简单地写'fun',否则我必须明确地说我正在传递一个函数。感谢所有人的明确答复! – Manu
@Manu:考虑接受一个你认为是最好的答案(不一定是这个答案) –