を必要なときに、完全にオブジェクトの型パラメータを無視する方法は:スカラ - 次のScala 2.11のコードを考える
class Partials {
class Aggregate
class AggregateId[T <: Aggregate]
class Event[T <: Aggregate]
type EventListener = PartialFunction[Event[_], Unit]
val listeners = mutable.Set[EventListener]()
def addListener(l: EventListener) {
listeners += l
}
def process(e: Event[_]): Unit = {
listeners.foreach(listener => if (listener.isDefinedAt(e)) listener.apply(e))
}
addListener {
case x => println(x)
}
}
これは私の実際のコード、いくつかのイベント処理から簡略化されているが、それは同じ問題を示しています。いくつかの集計を参照するイベントがあり、これらのイベントを処理できるリスナーがあります。リスナーはPartialFunctionsであるため、Eventサブタイプの一部を処理できますが、すべてを処理することはできません。記載されているとおり
、私は終わりのaddListenerの呼び出しのために、次のエラーを取得しています:
type arguments [_$1] do not conform to class Event's type parameter bounds [T <: Partials.this.Aggregate]
addListener {
私は
type EventListener = PartialFunction[Event[_ <: Aggregate], Unit]
にEventListener
タイプの別名を変更すると、私が代わりに次のエラーが出ますprocess
方法:
Error:(19, 60) type mismatch;
found : Partials.this.Event[_$2] where type _$2
required: Partials.this.Event[_ <: Partials.this.Aggregate]
listeners.foreach(listener => if (listener.isDefinedAt(e)) listener.apply(e))
Error:(19, 79) type mismatch;
found : Partials.this.Event[_$2] where type _$2
required: Partials.this.Event[_ <: Partials.this.Aggregate]
listeners.foreach(listener => if (listener.isDefinedAt(e)) listener.apply(e))
現時点では何が起こっているのか分かりません。 Event
は、これと無関係なものに対して型パラメータを必要としますが、イベントを処理するはずのPartialFunctionsでは、私は[_]
で行ったと思った型パラメータを単に無視したいと思います。私は何が間違っていますか?
ありがとう、それは私には完璧な意味があります。私はエラーを見ている場所だけでなく、型宣言をチェックする習慣を身につける必要があります。 –