Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala tailrec annotation error

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.

like image 693
Ralph Avatar asked Nov 30 '22 17:11

Ralph


1 Answers

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.

like image 134
Martin Odersky Avatar answered Dec 09 '22 23:12

Martin Odersky