listen メソッドの 2 番目の呼び出しが機能しない理由を説明し、それを機能させるための解決策を提案していただけますか?
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") }