1
考虑下面的斯卡拉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 {
当我改变EventListener
类型别名
type EventListener = PartialFunction[Event[_ <: Aggregate], Unit]
我反而得到以下错误在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,我想简单地忽略那个类型参数,这是我认为我用[_]
所做的。我错了什么?
谢谢,这对我来说非常有意义。我需要养成检查类型声明的习惯,而不仅仅是在看到错误的地方。 –