继承消息处理行为

发布于 2024-12-05 03:36:19 字数 808 浏览 2 评论 0原文

我的模型中有一些事件和一些处理逻辑。我想组织通信逻辑抛出演员。但是我如何继承处理逻辑而不在每个具体类中指定 act()

简化示例

class Event {}

case class FooEvent(str : String) extends Event
case class BarEvent(i : java.lang.Integer) extends Event

trait FooListener extends Actor {
  def act() {
    react{
      case FooEvent => print("foo received")
    }
  }
}
trait BarListener extends Actor {
  def act() {
    react{
      case BarEvent => print("bar received")
    }
  }
}
class ListensOnlyBar extends BarListener{}

//can't be done: 
//error: overriding method act in trait FooListener of type ()Unit;
//method act in trait BarListener of type ()Unit needs `override' modifier
//class ListensBarAndFoo extends FooListener with BarListener{
class ListensBarAndFoo extends FooListener with BarListener{}

I have some events in my model and some handling logic. I want organize communication logic throw Actors. But how I can inherit handling logic without specifying act() in each concrete class

Simplified example

class Event {}

case class FooEvent(str : String) extends Event
case class BarEvent(i : java.lang.Integer) extends Event

trait FooListener extends Actor {
  def act() {
    react{
      case FooEvent => print("foo received")
    }
  }
}
trait BarListener extends Actor {
  def act() {
    react{
      case BarEvent => print("bar received")
    }
  }
}
class ListensOnlyBar extends BarListener{}

//can't be done: 
//error: overriding method act in trait FooListener of type ()Unit;
//method act in trait BarListener of type ()Unit needs `override' modifier
//class ListensBarAndFoo extends FooListener with BarListener{
class ListensBarAndFoo extends FooListener with BarListener{}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅浅 2024-12-12 03:36:19

react 需要 PartialFunction[Any, Unit] 并且您可以很好地将它们组合在一起。这是一个例子:

type Listener = PartialFunction[Any, Unit]

val foo: Listener = {
  case FooEvent => print("foo received")
}

val bar: Listener = {
  case BarEvent => print("bar received")
}

case class GenericListener(listener: Listener) extends Actor {
  def act() {
    react(listener)
  }
}

GenericListener(bar)
GenericListener(foo orElse bar)

react expects PartialFunction[Any, Unit] and you can nicely compose them together. Here is an example:

type Listener = PartialFunction[Any, Unit]

val foo: Listener = {
  case FooEvent => print("foo received")
}

val bar: Listener = {
  case BarEvent => print("bar received")
}

case class GenericListener(listener: Listener) extends Actor {
  def act() {
    react(listener)
  }
}

GenericListener(bar)
GenericListener(foo orElse bar)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文