2016-05-14 111 views
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,我想简单地忽略那个类型参数,这是我认为我用[_]所做的。我错了什么?

回答

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方法是如何定义的。这些错误消息告诉您,当您将listener的类型定义为PartialFunction[Event[_ <: Aggregate], Unit]时,则需要将Event[_ <: Aggregate]的实例传递给listenerisDefinedAtapply方法。

+0

谢谢,这对我来说非常有意义。我需要养成检查类型声明的习惯,而不仅仅是在看到错误的地方。 –