Observer pattern or callback is a widely used design pattern in Java. However, implementing callback interface with anonymous class is a real pain, so it is common in Scala that introducing implicit conversion for these callback class implementation. For example, implicit conversion for Runnable interface is:
implicit def func2Runnable[F](f: => F): Runnable =
new Runnable {
def run() {
f
}
}
And suppose that there are some listener registry:
def addMyListener(m: Runnable) {
// mock function for test
for (i <- 1 to 2) {
m.run()
}
}
Then implicit conversion magically compacted my code:
addMyListener(println("Printed twice"))
Problem:
When I pass multi-line code block to addMyListener(), only the last line of code is passed to it:
addMyListener {
println("This line is printed once")
println("Only this is printed twice")
}
Known workaround:
I added a parenthesis on the conversion function:
implicit def func2Runnable[F](f:() => F): Runnable =
new Runnable {
def run() {
f()
}
}
But it is verbose when we use it:
addMyListener(() => println("Printed twice"))
addMyListener {() =>
println("This line is printed twice")
println("This is also printed twice")
}
Is there a cleaner solution to expose this?