gpt4 book ai didi

scala - 带有 Scala 延续的事件监听器

转载 作者:行者123 更新时间:2023-12-04 17:04:32 26 4
gpt4 key购买 nike

假设我必须编写一些 GUI 代码,如下所示:

widget1.addListener(event1 =>
handle1(event1)
widget2.addListener(event2 =>
handle2(event2)
widget3.addListener(event3 => handle3(event3))
)
)

您将如何使用 Scala 延续以 CPS 风格编写它?

最佳答案

除了其他答案之外,只想提供工作示例。使用 Scala 延续,它看起来像这样:

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))
}

这段代码实际上可以编译并运行,因此您可以自己尝试一下。您应该收到以下输出:
Handling first event: Event(event for first widget)
Handling second event: Event(event for second widget)
Handling first event: Event(one more event)

如果您将编译此示例,请不要忘记通过提供 -P:continuations:enable 来启用延续。 Scala 编译器的参数。

关于scala - 带有 Scala 延续的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6062003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com