最近,我在 Scala 中玩过类型级编程,发现如下:
trait NextPage[Curr, Next] {
def next : Next
}
class Foo
class Bar
class X(val year : Int)
object X {
implicit def xToNextPage[Y](x : X) : NextPage[X, Y] =
if (x.year == 2010) {
new X(x.year) with NextPage[X, Bar] {
def next = new Bar
}
}
else {
new X(x.year) with NextPage[X, Foo] {
def next = new Foo
}
}
}
val x = new X(2010)
val y = x.next //BOOM!
最后一行无限期地冻结解释器。奇怪的是,如果你只改变一行代码:
implicit def xToNextPage[Y](x : X) : NextPage[X, Y] =
到那个
implicit def xToNextPage(x : X) : NextPage[X, _] =
计算将成功执行(但结果类型当然会丢失)。
你知道为什么会这样吗?我相信,它以某种方式与类型推断有关......