问题
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.
回答1:
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.
回答2:
May I suggest a more succinct version of the code?
def getDbTableForClass[A <: ImmutableEntity](cls: Class[A]): String = {
@tailrec
def getDbTableAnnotation[B >: A](cls: Class[B]): DBTable = cls match {
case null => null
case c if c.isAnnotationPresent(classOf[DBTable]) => c.getAnnotation(classOf[DBTable])
case other => getDbTableAnnotation(other.getSuperclass)
}
getDbTableAnnotation(cls) match {
case null => throw new IllegalArgumentException("No DBTable annotation on class " + cls.getName)
case dbTable if dbTable.value ne null => dbTable.value
case other => throw new IllegalArgumentException("No DBTable.value annotation on class " + cls.getName)
}
}
回答3:
Since the type parameter B and its bound aren't strictly required, you can use an existential type instead,
@tailrec
def getDbTableAnnotation(cls: Class[_]): DBTable = {
...
}
Scala accepts this definition for tail-recursive calls.
来源:https://stackoverflow.com/questions/4520781/scala-tailrec-annotation-error