gpt4 book ai didi

scala - Scala中final var的用法是什么

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

final var的用法是什么在斯卡拉?什么行为。有任何用例吗?

(另见 Why are `private val` and `private final val` different? ,非常接近,但不一样)

最佳答案

final有过重的意义。

它可能意味着“不能在子类中覆盖”,因此 final var .

apm@mara:~$ skala -Yoverride-vars
Welcome to Scala version 2.11.0-20130811-132927-95a4d6e987 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> trait Foo { var v = 7 }
defined trait Foo

scala> trait Bar extends Foo { override var v = 8 }
defined trait Bar

scala> trait Foo { final var v = 7 }
defined trait Foo

scala> trait Bar extends Foo { override var v = 8 }
<console>:8: error: overriding variable v in class Foo$class of type Int;
variable v cannot override final member
trait Bar extends Foo { override var v = 8 }
^
final val i = 7是一个常量值定义(又名编译时常量)但是 val i = 7不是,无论访问修饰符如何。

之前已经引用过这一点,但是,规范的 5.2:

The final modifier applies to class member definitions and to class defini- tions. 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 ob- ject 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 (§4.1) do require an explicit final modifier, even if they are defined in a final class or object. final may not be applied to incom- plete members, and it may not be combined in one modifier list with sealed.



和 4.1

A constant value definition is of the form


final val x = e

where e is a constant expression (§6.24). The final modifier must be present and no type annotation may be given. References to the constant value x are themselves treated as constant expressions; in the generated code they are replaced by the def- inition’s right-hand side e.



编辑:对不起,没有注意到你特别没有问这个。 children 正准备 sleep 、刷牙等等,有点心不在焉。

关于scala - Scala中final var的用法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18222233/

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