【发布时间】:2015-03-09 13:20:07
【问题描述】:
试图让 F-Bounded Polymorphism 在 Scala 中按我想要的方式工作,我快疯了。
以下代码将无法编译:
object TestTypeBounds {
trait Upper[T <: Upper[T]] {
def map() : T
}
class Impl extends Upper[Impl] {
def map() : Impl = this
}
type Arr = Upper[T] forSome {type T <: Upper[T]}
def testBounds() {
// Though any is specified as the type parameter, the definition of Upper specifies
// an upper bound of Upper
val upper: Upper[_] = new Impl()
// This must 'logically' be an Upper, but the compiler thinks it's an Any
val mapped = upper.map()
// This line will fail!
mapped.map().map().map()
}
def main(args: Array[String]): Unit = {
testBounds()
}
}
这里的问题是编译器抱怨映射的类型是Any,因此它没有方法映射。我不清楚为什么编译器不分配映射类型 Upper,因为这实际上是 Upper 参数类型的类型上限,即使在此实例中指定了任何类型。
请注意,用别名 Arr 替换“val upper...:”的类型是可行的,因为现在 Scala 可以看到该类型是递归的,并且始终是 Upper。不幸的是,这种方法对我也不起作用,因为我正在实现一个将 Upper[_] 参数传递给函数的 Java 库,然后这些会遇到上述问题。编译器也不接受这些函数被覆盖为具有“Arr”参数的代码,即别名在这种情况下不起作用。
编辑:最后一段并不完全正确,请看下面我的回答
【问题讨论】:
标签: scala generics polymorphism