在 Scala 中,final val 和 val 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24911664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:26:00  来源:igfitidea点击:

In Scala, difference between final val and val

scalaimmutability

提问by elm

In Scala, what is the difference between

在Scala中,有什么区别

val a = 1

and

final val fa = 1

回答by Michael Zajac

finalmembers cannot be overridden, say, in a sub-class or trait.

final成员不能被覆盖,例如,在子类或特征中。

Legal:

合法的:

class A {
    val a = 1
}

class B extends A {
    override val a = 2
}

Illegal:

非法的:

class A {
    final val a = 1
}

class B extends A {
    override val a = 2
}

You'll get an error such as this:

你会得到这样的错误:

:9: error: overriding value a in class A of type Int(1);

value a cannot override final member

:9: 错误:覆盖类型为 Int(1) 的 A 类中的值 a;

值 a 不能覆盖最终成员

回答by wingedsubmariner

In Scala, finaldeclares that a member may not be overridden in subclasses. For example:

在 Scala 中,final声明一个成员不能在子类中被覆盖。例如:

class Parent {
  val a = 1
  final val b = 2
}

class Subclass extends Parent {
  override val a = 3 // this line will compile
  override val b = 4 // this line will not compile
}

Also, as discussed in Why are `private val` and `private final val` different?, if a final valfield is holding a "constant value", a constant primitive type, access to it will be replaced with the bytecode to load that value directly.

另外,正如为什么`private val`和`private final val`不同?, 如果一个final val字段持有一个“常量值”,一个常量原始类型,对它的访问将被替换为字节码以直接加载该值。

回答by Jin

You also cannot use non-finalvals in (Java) annotations.

您也不能finalval在 (Java) 注释中使用 non- s。

For example, this:

例如,这个:

@GameRegistry.ObjectHolder(Reference.MOD_ID)
object ModItems{
}

will only compile if MOD_IDis declared as final.

仅当MOD_ID声明为final.