方法的通用超类型

Common supertype of methods

考虑以下定义:

trait Event
case class Event1[A] extends Event
case class Event2[A, B] extends Event
/* ... */

trait Filter { val cond: Event => Boolean }
case class Filter1[A](cond: Event1[A] => Boolean) extends Filter
case class Filter2[A, B](cond: Event2[A, B] => Boolean) extends Filter
 /* ... */

我想我想在这里完成的很清楚:我想确保每当我遇到 Filter 时,它都保证有一个 cond 函数接受Event 的相应子类型并给了我一个布尔值。显然,上面的代码无法编译,例如,Event1[A] => Boolean 实际上并不是 Event => Boolean 的子类型。如何解决这样的问题?

像下面这样的东西怎么样?

sealed trait Event
case class Event1[A]() extends Event
case class Event2[A, B]() extends Event
/* ... */

sealed trait Filter[T <: Event] { val cond: T => Boolean }
case class Filter1[A](cond: Event1[A] => Boolean) extends Filter[Event1[A]]
case class Filter2[A, B](cond: Event2[A, B] => Boolean) extends Filter[Event2[A, B]]

或者,您可以覆盖抽象类型而不是使用参数化类型:

sealed trait Filter {
  type Filterable
  val cond: Filterable => Boolean
}
case class Filter1[A](cond : Event1[A] => Boolean) extends Filter{
  override type Filterable = Event1[A]
}

case class Filter2[A, B](cond: Event2[A, B] => Boolean) extends Filter{
  override type Filterable = Event2[A, B]
}

试试这个:

  trait Event
  case class Event1[A](a: A) extends Event
  case class Event2[A, B](a: A, b: B) extends Event

  trait Filter[T <: Event] { val cond: T => Boolean }
  case class Filter1[A](cond: Event1[A] => Boolean) extends Filter[Event1[A]]
  case class Filter2[A, B](cond: Event2[A, B] => Boolean) extends Filter[Event2[A, B]]

它为我编译