通过Akka演员获得正确的变化?

时间:2017-10-01 05:52:00

标签: scala akka scala-generics f-bounded-polymorphism

在使用泛型和Akka actor时,我经常遇到以下问题:

trait AuctionParticipantActor[P <: AuctionParticipant[P]]
  extends StackableActor {


  override def receive: Receive = {
    case message: Handled =>
      participant = participant.handle(message)
      super.receive(message)
    case message =>
      super.receive(message)
  }

  protected var participant: P

}

AuctionParticipantActor只是不可变AuctionParticipant的包装。我需要类型P是协变的,我不确定实现这一目标的最佳方法是什么。

或者,对于我的用例,我不认为我甚至需要参数化AuctionParticipantActor。我可以有类似的东西:

trait AuctionParticipantActor
  extends StackableActor {


  override def receive: Receive = {
    case message: Handled =>
      participant = participant.handle(message)
      super.receive(message)
    case message =>
      super.receive(message)
  }

  protected var participant: AuctionParticipant[???]

}

但在这种情况下,我不知道该取代什么?为了尊重类型的约束。如果有人认为我的问题与设计有关,请说出来。想法?

1 个答案:

答案 0 :(得分:0)

如果您不使用f-bounded-polymorphism,为什么需要AuctionParticipant为通用名称?那么P中类型参数AuctionParticipant[P]的含义是什么?如上所述,如果AuctionParticipantActor仅仅是AuctionParticipant的封装,如果AuctionParticipantActor不再是通用的,那么AuctionParticipant也不应该是。{/ p>

trait AuctionParticipantActor
  extends StackableActor {


  override def receive: Receive = {
    case message: Handled =>
      participant = participant.handle(message)
      super.receive(message)
    case message =>
      super.receive(message)
  }

  protected var participant: AuctionParticipant

}

trait AuctionParticipant {
  // ...
}

否则如果AuctionParticipant仍然是通用的(即P还有其他含义),那么您可以使用existential type

trait AuctionParticipantActor
  extends StackableActor {


  override def receive: Receive = {
    case message: Handled =>
      participant = participant.handle(message)
      super.receive(message)
    case message =>
      super.receive(message)
  }

  protected var participant: AuctionParticipant[_]

}

trait AuctionParticipant[P] {
  // ...
}