在运行时我可以:
def X(R: Any): Any = X(R)
但是编译时不能做同样的事情:
scala> type X[R] = X[R]
<console>:11: error: illegal cyclic reference involving type X
type X[R] = X[R]
^
看起来像无限循环/递归保护,但据我所知Halting problem - 没有通用的方法来检测turing-complete语言的无限递归(因为检测器本身可能不会停止),所以额外的编译器检查通常不会在这里工作。
那么有没有办法在scalac上获得无限递归?而且,还有其他(除了阻止这种递归)理由有illegal cyclic reference
吗?
答案 0 :(得分:0)
使用递归和多态性在scalac上获取StackOverflow有一种棘手的方法:
scala> trait Re { type X[R <: Re] }
warning: there were 1 feature warning(s); re-run with -feature for details
defined trait Re
scala> trait ReRe extends Re {type X[R <: Re] = R#X[R]}
defined trait ReRe
scala> type X = ReRe#X[ReRe]
java.lang.StackOverflowError
它之所以有效,是因为编译器认为在R#X[R]
上调用了Re
,但在计算ReRe
时实际上已经传递了type X
。
不知道illegal cyclic reference
的目的 - 也许它只保护编译器内部的无限循环,而不是来自无限递归(如果使用非尾递归实现turing-completeness)。