ipos de métodos Scala e métodos como parâmetro
No exemplo de código a seguir, não entendo por que a função fun pode ser passada como argumento para o métodoaddAction
. O métodofun
é do tipoUnit
, enquanto o métodoaddAction
espera uma função do tipo() => Unit
.
E sefun
é do tipo() => Unit
, por que o compilador reclama quefun
é do tipoUnit
, quando tento adicionarfun
para a lista de ações: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"
}
}