2016-05-14 12 views
1

を必要なときに、完全にオブジェクトの型パラメータを無視する方法は:スカラ - 次の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では、私は[_]で行ったと思った型パラメータを単に無視したいと思います。私は何が間違っていますか?

答えて

4

これは動作するようです:

import scala.collection.mutable 

class Partials { 
    class Aggregate 
    class AggregateId[T <: Aggregate] 
    class Event[T <: Aggregate] 

    type EventListener = PartialFunction[Event[_ <: Aggregate], Unit] 

    val listeners = mutable.Set[EventListener]() 

    def addListener(l: EventListener) { 
    listeners += l 
    } 

    def process(e: Event[_ <: Aggregate]) { 
    listeners.foreach(listener => if (listener.isDefinedAt(e)) listener.apply(e)) 
    } 

    addListener { 
    case x => println(x) 
    } 
} 

processメソッドが定義されているかに注意してください。これらのエラーメッセージは、のタイプをPartialFunction[Event[_ <: Aggregate], Unit]と定義すると、Event[_ <: Aggregate]のインスタンスをlistenerisDefinedAtapplyのメソッドに渡す必要があることを示していました。

+0

ありがとう、それは私には完璧な意味があります。私はエラーを見ている場所だけでなく、型宣言をチェックする習慣を身につける必要があります。 –

関連する問題