scala - 如何在需要时完全忽略对象的类型参数

时间:2016-05-14 23:37:13

标签: scala pattern-matching type-parameter

给出以下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 {

当我将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需要与其无关的事物的类型参数,但是对于应该处理事件的PartialFunction,我想简单地忽略那个类型参数,这就是我认为我对{{{ 1}}。我错了什么?

1 个答案:

答案 0 :(得分:4)

这似乎有效:

<?php
    header("Content-type: text/css");
    $url = "http://sitename.com/files/greenbutton.png";
    $colore = "#000000";
?>
a
  { background: <?php=$url;?>; 
color: <?php=$colore;?>;   }

注意如何定义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]&#39; listenerisDefinedAt方法。