为什么对象内部的val不会自动结束? [英] Why is a `val` inside an `object` not automatically final?

查看:85
本文介绍了为什么对象内部的val不会自动结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

val不能在单例对象中自动结束的原因是什么?例如

What is the reason for vals not (?) being automatically final in singleton objects? E.g.

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

编译时没有警告,因此大概会生成更快的模式匹配表.

Compiles without warnings, so presumably generates the faster pattern matching table.

必须添加final似乎使我感到讨厌. object决赛本身不是吗,因此它的成员也不是吗?

Having to add final seems pure annoying noise to me. Isn't an object final per se, and thus also its members?

推荐答案

此规范在规范中得到了明确解决. ,它们将自动成为最终版本:

This is addressed explicitly in the specification, and they are automatically final:

final类或对象的成员也隐式也是final,因此 final修饰符对他们来说通常也是多余的.但是请注意, 常量值定义(第4.1节)确实需要显式的final修饰符,即使 它们是在最终类或对象中定义的.

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.

您的final -less示例使用2.10-M7编译时没有错误(或警告),因此我认为@switch的较早版本检查存在问题,并且成员实际上是最终的.

Your final-less example compiles without errors (or warnings) with 2.10-M7, so I'd assume that there's a problem with the @switch checking in earlier versions, and that the members are in fact final.

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

Update: Actually this is more curious than I expected—if we compile the following with either 2.9.2 or 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();
}

即使值定义的右侧不是常量表达式,您也会看到相同的东西.

You see the same thing even if the right-hand side of the value definitions isn't a constant expression.

所以我将留下答案,但这不是结论性的.

So I'll leave my answer, but it's not conclusive.

这篇关于为什么对象内部的val不会自动结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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