开发者

Scala class with Publisher and Subscriber traits

Using import scala.collection.mutable.{Publisher, Subscriber} I'm trying to implement a cla开发者_高级运维ss that subscribes to events and publishes events. For example, this class may receive raw data, operate on it, then publish the result to other subscribers.

A basic class that extends Subscriber:

scala> class Sub[Evt, Pub]() extends Subscriber[Evt, Pub]{
  def notify(pub: Pub, evt: Evt){
  }
}
defined class Sub

A basic class that extends Publisher:

scala> class Pub[Evt]() extends Publisher[Evt]{}
defined class Pub

Now, I want to combine the two:

scala> class PubSub[Evt, Pub] extends Subscriber[Evt, Pub] with Publisher[Evt]{
  def notify(pub: Pub, evt: Evt){
  }
}
<console>:26: error: class PubSub needs to be abstract, since method notify in
trait Subscriber of type (pub: Pub,event: Evt)Unit is not defined class 
PubSub[Evt,Pub] extends Subscriber[Evt, Pub] with Publisher[Evt]{

The notify method is defined so perhaps the error is misleading.

I'm not sure how to define the type parameters for the PubSub class which might be part of the problem.


The problem is that the class Publisher defines a type Pub which shadows the generic Pub argument.

Just rename it to something else:

class PubSub[Evt, Pub2] extends Subscriber[Evt, Pub2] with Publisher[Evt]{
  def notify(pub: Pub2, evt: Evt){
  }
}


You should take a look at the paper Deprecating the Observer Pattern I believe. scala.react package described there isn't released as a part of the standard distribution, but some snapshot is available on the author's homepage. If you are not planning to use it in production systems right now this project can give a sufficient playground.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜