Scala tailrec注释错误
我有一个名为 ImmutableEntity
的 Java 抽象类和几个包含名为 @DBTable
的类级注释的子类。我正在尝试使用尾递归 Scala 方法在类层次结构中搜索注释:
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)
}
}
}
当我编译此代码时,我收到错误:“无法优化 @tailrec 带注释的方法:它使用不同类型的参数递归调用”。我的内在方法有什么问题吗?
谢谢。
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)
}
}
}
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?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为编译器通过循环实现尾递归的方式。这是作为从 Scala 到 Java 字节码的一系列转换中的一个步骤来完成的。每次转换都必须生成一个类型再次正确的程序。但是,如果您无法在循环执行中更改变量的类型,这就是编译器无法扩展为类型正确的循环的原因。
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.
我可以建议一个更简洁的代码版本吗?
}
May I suggest a more succinct version of the code?
}
由于类型参数
B
及其绑定并不是严格必需的,因此您可以使用存在类型来代替,Scala 接受尾递归调用的此定义。
Since the type parameter
B
and its bound aren't strictly required, you can use an existential type instead,Scala accepts this definition for tail-recursive calls.