斯卡拉tailrec标注错误 [英] Scala tailrec annotation error
问题描述
我 ImmutableEntity
调用的Java抽象类和含有称为类级别注解几个子类 @DBTable
。我试图用尾递归方法斯卡拉搜索注释的类层次结构:
I have a Java abstract class called ImmutableEntity
and several subclasses that contain a class-level annotation called @DBTable
. I am trying to search a class hierarchy for the annotation using a tail-recursive Scala method:
def getDbTableForClass[A <: ImmutableEntity](cls: Class[A]): String = {
@tailrec
def getDbTableAnnotation[B >: A](cls: Class[B]): DBTable = {
if (cls == null) {
null
} else {
val dbTable = cls.getAnnotation(classOf[DBTable])
if (dbTable != null) {
dbTable
} else {
getDbTableAnnotation(cls.getSuperclass)
}
}
}
val dbTable = getDbTableAnnotation(cls)
if (dbTable == null) {
throw new
IllegalArgumentException("No DBTable annotation on class " + cls.getName)
} else {
val value = dbTable.value
if (value != null) {
value
} else {
throw new
IllegalArgumentException("No DBTable.value annotation on class " + cls.getName)
}
}
}
当我编译这个code,我得到的错误:无法优化@tailrec标注的方法:它是递归与不同类型的参数调用。什么是错的我内心的方法是什么?
When I compile this code, I am getting the error: "could not optimize @tailrec annotated method: it is called recursively with different type arguments". What is wrong with my inner method?
感谢。
推荐答案
这是因为编译器实现由环尾递归的方式。这是作为转换的链条,从斯卡拉Java字节codeS一步完成。每个转换必须产生一个程序,再次的Type-正确的。但是,你不能改变的变量类型中旬循环执行,这就是为什么编译器不能扩展到一个类型正确的循环。
It's because of the way the compiler implements tail-recursion by loops. This is done as one step in a chain of transformations from Scala to Java bytecodes. Each transformation must produce a program that's again type-correct. However, it you can't change the type of variables in mid-loop execution, that's why the compiler could not expand into a type-correct loop.
这篇关于斯卡拉tailrec标注错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!