简体   繁体   English

常见的方法超类

[英]Common supertype of methods

Consider the following definitions: 请考虑以下定义:

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
 /* ... */

I think it is quite clear what I am trying to accomplish here: I want to make sure that whenever I encounter a Filter , it is guaranteed to have a cond function that takes the respective subtype of Event and gives me a Boolean. 我想我在这里要完成的工作很清楚:我想确保每次遇到Filter ,都保证有一个cond函数,该函数接受Event的相应子类型并给我一个布尔值。 Obviously, the code above doesn't compile as, for example, Event1[A] => Boolean is not really a subtype of Event => Boolean . 显然,上面的代码无法编译,例如, Event1[A] => Boolean实际上不是Event => Boolean的子类型。 How would one solve such an issue? 一个人将如何解决这一问题?

How about something like the following? 如下所示呢?

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

Alternatively, you could override an abstract type instead of using parametrized types: 或者,您可以覆盖抽象类型,而不是使用参数化类型:

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

Try this: 尝试这个:

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

It compiled for me 它为我编译

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM