常见的超类方法

时间:2017-01-27 16:03:12

标签: scala generics types generic-programming

考虑以下定义:

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的子类型。如何解决这个问题呢?

2 个答案:

答案 0 :(得分:2)

如下所示:

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]
}

答案 1 :(得分:0)

试试这个:

  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]]

它为我编译