Scala tipos de métodos y métodos como parámetros
En el siguiente ejemplo de código, no entiendo por qué la función fun se puede pasar como argumento al métodoaddAction
. El métodofun
es de tipoUnit
, mientras que el métodoaddAction
espera una función de tipo() => Unit
.
Sifun
es de tipo() => Unit
, entonces ¿por qué el compilador se queja de quefun
es de tipoUnit
, cuando intento agregarfun
a la lista de acciones: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"
}
}