在下面的代碼示例中,我不明白爲什麼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:考慮接受一個你認爲是最好的答案(不一定是這個答案) –