考虑以下定义:
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
的子类型。如何解决这个问题呢?
答案 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]]
它为我编译