Scala tailrec 注释错误 [英] Scala tailrec annotation error

查看:29
本文介绍了Scala tailrec 注释错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 ImmutableEntity 的 Java 抽象类和几个包含名为 @DBTable 的类级注释的子类.我正在尝试使用尾递归 Scala 方法搜索注释的类层次结构:

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)
      }
    }
  }

当我编译此代码时,出现错误:无法优化@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?

谢谢.

推荐答案

这是因为编译器通过循环实现尾递归的方式.这是从 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.

这篇关于Scala tailrec 注释错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆