给定具有绑定类型参数Animal [A<:String]的类定义,似乎
Scala编译器不会从Animal [B]推断出B<:String.是否允许推理?如何帮助编译器进行推理? 下面是一个案例类的具体示例,其中缺少此推断是一个问题. 考虑以下案例类层次结构:
sealed trait Person[+T <: Person[T]] case class Student() extends Person[Student] case class Professor() extends Person[Professor]
我需要定义一个case类University,我可以使用Person [_]类型的变量进行实例化,例如val p:Person [_] = Student().我认为这可以使用以下定义:
case class University(p: Person[_])
但这无法编译错误:
type arguments [Any] do not conform to trait Person's type parameter bounds [+T <: Person[T]]
如果我绑定了案例类大学的类型参数,它会编译(如果我删除case关键字,它也会使用无界参数编译,但在我的情况下这不是一个选项):
case class BoundUniversity[P <: Person[P]](p: Person[P])
但是这个参数化版本无法使用Person [_]类型的无界变量进行实例化:
val p: Person[_] = Student() BoundUniversity(p)
编译失败:
inferred type arguments [_$1] do not conform to method apply's type parameter bounds [P <: Person[P]]
def general[P <: Person[P]](p: P) = println(p)
所以这不是类构造函数特有的.
两个问题:
>使用参数bounds Person [T<:Person [T]]定义Person类型,以便保证此类型的每个实例都遵守这些边界:val p:Person [P]暗示P< ;: Person [ P];还是我错过了什么?那么我怎样才能让编译器明白这一点,以免它抱怨?
>如何/我可以定义具有未绑定类型参数的成员的案例类,例如案例类大学(p:Person [_])?
解决方法
类型X [_]几乎不是你想要的.当你在一个类型上使用_时,你基本上是说你不关心那个参数是什么,因为你永远不需要使用它.
无论如何,这编译.它可能会让你不顾一切,存在类型是它们的棘手问题,但……
case class University(p: Person[t] forSome { type t <: Person[t] })