@tailrec为什么这个方法不能用'包含一个不在尾部位置的递归调用'编译? [英] @tailrec why does this method not compile with 'contains a recursive call not in tail position'?
本文介绍了@tailrec为什么这个方法不能用'包含一个不在尾部位置的递归调用'编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@tailrec
private def loop[V](key: String): V = {
key match {
case _ => loop(key)
}
}
这种方法不能编译和抱怨说它'包含一个不在尾部位置的递归调用'。有人可以向我解释发生了什么事吗?这个错误信息对我来说没有意义。
This method doesn't compile and complains that it 'contains a recursive call not in tail position'. Can someone explain to me what's going on? This error message doesn't make sense to me.
推荐答案
如果指定了泛型类型,它就编译好:
It compiles ok if the generic type is specified:
import scala.annotation.tailrec
@tailrec
private def loop[V](key: String): V = {
key match {
case _ => loop[V](key)
}
}
我认为错误消息在这种情况下是误导性的。
I think the error message is misleading in this case.
一个简化的版本给出了一个更好的提示:
A simplified version gives a better hint on what's going on:
scala> @tailrec
| private def loop[V](key: String): V = {
| loop(key)
| }
<console>:14: error: could not optimize @tailrec annotated method loop: it is called recursively with different type arguments
loop(key)
^
这篇关于@tailrec为什么这个方法不能用'包含一个不在尾部位置的递归调用'编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文