gpt4 book ai didi

scala - Scala ObservableSet Trait 的使用示例

转载 作者:行者123 更新时间:2023-12-04 22:52:11 24 4
gpt4 key购买 nike

谁能帮我告诉我如何使用scala的 ObservableSet 特征?

非常感谢您提前

最佳答案

ObservableSet是从 Publisher 延伸的特征trait,提供一些基本的发布订阅行为。使用它的一个简单示例是:

scala> class Counter(var count: Int) extends Publisher[String] {
def inc(): Unit = {
count += 1
super.publish("updated count to: " + count)
}
}

scala> class S[Evt, Pub] extends Subscriber[Evt, Pub] {
def notify(pub: Pub, event: Evt): Unit = println("got event: " + event)
}
defined class S

scala> val s = new S[String, Counter#Pub]
s: S[String,Counter#Pub] = S@7c27a30c

scala> val c = new Counter(1)
c: Counter = Counter@44ba70c

scala> c.subscribe(s)

scala> c.inc
got event: updated count to: 2

ObservableSet 做了类似的事情,它在使用 += 或 +- 方法添加或删除元素时调用发布方法,请参见以下示例(类 S 定义如上):
scala> class MySet extends HashSet[Int] with ObservableSet[Int] {       
override def +=(elem: Int): this.type = super.+=(elem);
override def -=(elem: Int): this.type = super.-=(elem);
override def clear: Unit = super.clear;
}

defined class MySet

scala> val set = new MySet
set: MySet = Set()

scala> val subS = new S[Any, Any]
subCol: S[Any,Any] = S@3e898802

scala> set.subscribe(subS)

scala> set += 1
got event: Include(NoLo,1)
res: set.type = Set(1)

我通过使用 Any 类型定义 S 来变得懒惰,但我无法立即正确输入,并且没有花太长时间试图弄清楚。

关于scala - Scala ObservableSet Trait 的使用示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2944617/

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