gpt4 book ai didi

scala - 为什么Scala中的Final变量可以更改值

转载 作者:行者123 更新时间:2023-12-04 16:24:08 25 4
gpt4 key购买 nike

为什么在Scala中允许Final变量更改值。根据我的理解,一旦声明为final,就不应更改它们。

class foo()
{
final var name = "abc"
name = "xyz" // why this is allowed
}

最佳答案

每个Scala Specificationfinal定义(重点是我的):

5.2.6最终版

The final modifier applies to class member definitions and to class definitions. A final class member definition may not be overridden in subclasses. A final class may not be inherited by a template. final is redundant for object definitions. 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 do require an explicit final modifier, even if they are defined in a final class or object. final may not be applied to incomplete members, and it may not be combined in one modifier list with sealed.



由于Scala中的 val定义已经意味着对它的引用是不可变的(与Java不同),因此在定义它时不必显式指定它。如果要在字节码中将值作为常量内联,则可以指定添加 final修饰符。

根据 var,final在这里仅意味着“可能不会在子类中被覆盖”,但是对于变量的不变性却什么也没说:
scala> :pa
// Entering paste mode (ctrl-D to finish)

class Foo {
final var name = "abc"
}

class Bar extends Foo {
override var name = "yuval"
}

// Exiting paste mode, now interpreting.

<console>:16: error: overriding variable name in class Foo of type String;
variable name cannot override final member
override var name = "yuval"

关于scala - 为什么Scala中的Final变量可以更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42220569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com