您能否解释一下为什么第二次调用监听方法不起作用并提出解决方案以使其起作用?
object Example extends App {
case class Event(kind: Int)
trait Listener { def handle(e: Event) }
val listeners = scala.collection.mutable.Map[Int, Listener]()
def emit(e: Event) = listeners.get(e.kind).foreach(_.handle(e))
def listen(kind: Int)(f: (Event) => Unit) {
val l = new Listener() { override def handle(e: Event) = f(e) }
listeners += kind -> l
}
implicit def unit2EventUnit(f: => Unit) = (e: Event) => f
// This works as expected
println("1")
listen(1) { e: Event => println("a"); println("b") }
println("2")
emit(new Event(1))
println("3")
// Why this does not work? "c" should appear between "4" and "d", not "3" and "4"
listen(2) { println("c"); println("d") }
println("4")
emit(new Event(2))
println("5")
}
我知道这会起作用:
implicit def unit2EventUnit2(f: () => Unit) = (e: Event) => f()
listen(2) { () => println("c"); println("d") }
但这样写起来会更简单:
listen(2) { println("c"); println("d") }