Scala 泛型 "transmition"

Scala generic type "transmition"

像这样的通用定义

case class Event(a : Int)

trait EventHelper[B <: Event] {
   def getEvent : B
}
def genericFunction[T <: EventHelper[_]](x : T) = {
  x.getEvent.a
}

为什么 genericFunction 中的 B 被认为是 Any ?不应被视为事件?

我的解决方法是

def genericFunction[T <: EventHelper[B], B <: Event ](x : T) = {
  x.getEvent.a
}

但在我看来是多余的,不是吗?

当您说 T <: EventHelper[_] 时,您使用的是存在类型,需要特别注意定义上限和下限:

def genericFunction[T <: EventHelper[_ <: Event]](x : T) = x.getEvent.a

来自SLS:

Scala supports a placeholder syntax for existential types. A wildcard type is of the form _ >: L <: U. Both bound clauses may be omitted. If a lower bound clause >: L is missing, >: scala.Nothing is assumed. If an upper bound clause <: U is missing, <: scala.Any is assumed. A wildcard type is a shorthand for an existentially quantified type variable, where the existential quantification is implicit.

这意味着即使 EventHelper 的类型参数的上限为 Event_ 仍将被编译器推断为 Any 如果没有为其提供上限。