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

Scala中最终var的用法是什么?

发布时间:2020-12-16 09:53:21 所属栏目:安全 来源:网络整理
导读:Scala中最终var的用法是什么?什么是行为.有没有用例? (另见,Why are `private val` and `private final val` different?,非常接近,但不一样) 解决方法 决赛意义重大. 它可能意味着“不能在子类中覆盖”,因此最终变量. apm@mara:~$skala -Yoverride-varsWel
Scala中最终var的用法是什么?什么是行为.有没有用例?

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

解决方法

决赛意义重大.

它可能意味着“不能在子类中覆盖”,因此最终变量.

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.

编辑:抱歉,没有注意到你特意没有询问.孩子们正准备睡觉,刷牙,所有这一切,有点分心.

(编辑:李大同)

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

    推荐文章
      热点阅读