我有以下示例代码:
trait Recurse[T <: Recurse[T]] {
def method = "This is a method on recurse"
}
class Foo extends Recurse[Foo] {
override def toString = "This is a foo"
}
object Example {
def generate: Recurse[_ /*<: Recurse[_]*/] = new Foo()
def main(args: Array[String]) {
val foo = generate
foo match {
case m: Foo => println("match: " + m)
case _ => println("baa")
}
println(foo.method)
}
}
此代码在2.9.x上正确编译并运行(输出“匹配:这是一个foo”,后跟“这是一个递归方法”),但它在2.10.2上不起作用 . 相反,我得到编译时错误:类型参数[_ $ 1]不符合trait Recurse的类型参数bounds [T <:Recurse [T]]
有趣的是,问题只出现在模式匹配器中 . 如果我删除匹配块,代码编译并且代码输出“这是递归方法” .
更有趣的是模式匹配仍然无法编译,即使它中唯一的东西是默认情况!编译器根本不接受具有递归存在类型的对象用于模式匹配 . 但是,如果显式指定了foo的值(“val foo = new Foo()”),或者如果type参数不是递归的,那么代码甚至会在2.10上编译 .
这里发生了什么?为什么这会打破模式匹配,即使类型参数没有以任何方式参与匹配?有没有办法以2.10兼容的方式重写它?
2 回答
我相信这是Scala编译器的回归 . 为什么不file it?
这是SI-7716并在2.10.3和2.11中修复 .