在使用泛型和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[???]
}
但在这种情况下,我不知道该取代什么?为了尊重类型的约束。如果有人认为我的问题与设计有关,请说出来。想法?
答案 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] {
// ...
}