Just wanted to provide a working example in addition to the other answers. When continuing with Scala, it might look like this:
import scala.util.continuations._
object ContinuationsExample extends App {
val widget1 = Widget()
val widget2 = Widget()
reset {
val event1 = widget1.getEvent
println("Handling first event: " + event1)
val event2 = widget2.getEvent
println("Handling second event: " + event2)
}
widget2 fireEvent Event("should not be handled")
widget1 fireEvent Event("event for first widget")
widget2 fireEvent Event("event for second widget")
widget1 fireEvent Event("one more event")
}
case class Event(text: String)
case class Widget() {
type Listener = Event => Unit
var listeners : List[Listener] = Nil
def getEvent = shift { (l: Listener) =>
listeners = l +: listeners
}
def fireEvent(event: Event) = listeners.foreach(_(event))
}
This code actually compiles and runs, so you can try it yourself. You should get the following result:
Handling first event: Event(event for first widget)
Handling second event: Event(event for second widget)
Handling first event: Event(one more event)
If you compile this example, be sure to include continuations by providing an argument -P:continuations:enableto the Scala compiler.
source
share