0

在使用泛型和 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[???]

}

但在这种情况下,我不知道用什么代替???为了尊重类型绑定。如果有人认为我的问题出在设计上,请说出来。想法?

4

1 回答 1

0

If you don't use f-bounded-polymorphism why do you need AuctionParticipant to be generic? What is the meaning of type parameter P in AuctionParticipant[P] then? If, as you said, AuctionParticipantActor is just a wrapper over AuctionParticipant and if AuctionParticipantActor is no longer generic then maybe AuctionParticipant shouldn't be either.

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 {
  // ...
}

Otherwise if AuctionParticipant still should be generic (i.e. there is some other meaning of P) then maybe you can use 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] {
  // ...
}
于 2017-10-01T07:08:43.113 回答