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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With