jeudi 17 novembre 2016

How to statically register callbacks in Scala?

In C++ and Java one can implement a dispatcher-callback pattern with statically registered callbacks, thanks to the static members. In Scala, however, all objects are lazily initialized, so the code below doesn't really works as similar things in C++ or Java.

object Main {
    var callbacks = List[()=>Unit]()
    def main(args: Array[String]): Unit = {
        println("hello")
        callbacks.foreach { _() }
    }
}
object A {
    val callbackA = () => println("A")
    Main.callbacks = callbackA::Main.callbacks
}
object B {
    def callbackB = () => println("B")
    Main.callbacks = callbackB::Main.callbacks
}
object C {
    def callbackC = () => println("C")
    Main.callbacks = callbackC::Main.callbacks
}

When I run this program, none of the callbacks are invoked, because objects A, B, and C are never initialized and the registrations are never executed. Is there is a way in Scala to correctly implement what I intend here?

Aucun commentaire:

Enregistrer un commentaire