加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么`对象’中的`val`不会自动结束?

发布时间:2020-12-16 09:45:00 所属栏目:安全 来源:网络整理
导读:在单身对象中,vals不是(?)自动最终的原因是什么?例如。 object NonFinal { val a = 0 val b = 1 def test(i: Int) = (i: @annotation.switch) match { case `a` = true case `b` = false }} 结果是: console:12: error: could not emit switch for @swit
在单身对象中,vals不是(?)自动最终的原因是什么?例如。

object NonFinal {
   val a = 0
   val b = 1

   def test(i: Int) = (i: @annotation.switch) match {
      case `a` => true
      case `b` => false
   }
}

结果是:

<console>:12: error: could not emit switch for @switch annotated match
          def test(i: Int) = (i: @annotation.switch) match {
                                                     ^

而且

object Final {
   final val a = 0
   final val b = 1

   def test(i: Int) = (i: @annotation.switch) match {
      case `a` => true
      case `b` => false
   }
}

编译没有警告,所以可能产生更快的模式匹配表。

加入最后一点似乎是对我来说很烦人的噪音。本身不是一个对象,因此也是它的成员?

解决方法

这在 the specification年明确地解决了,它们是自动决定的:

Members of final classes or objects are implicitly also final,so
the final modifier is generally redundant for them,too. Note,however,that
constant value definitions (§4.1) do require an explicit final modifier,even if
they are defined in a final class or object.

你的最后一个例子使用2.10-M7编译没有错误(或警告),所以我假设@switch在早期版本中检查有问题,而且成员实际上是最终的。

更新:实际上,这比我预期的更好奇 – 如果我们用2.9.2或2.10-M7编译以下内容:

object NonFinal {
  val a = 0
}

object Final {
  final val a = 0
}

javap确实显示出不同之处:

public final class NonFinal$ implements scala.ScalaObject {
  public static final NonFinal$ MODULE$;
  public static {};
  public int a();
}

public final class Final$ implements scala.ScalaObject {
  public static final Final$ MODULE$;
  public static {};
  public final int a();
}

即使右侧的值定义不是一个常量表达式,你也会看到同样的事情。

所以我会留下我的答案,但这并不是决定性的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读