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

Scala初始化行为

发布时间:2020-12-16 09:23:29 所属栏目:安全 来源:网络整理
导读:请看下面的代码. trait MyTrait { val myVal : String }class MyClass extends MyTrait { val myVal = "Value" }class MyClass2(val myVal: String) extends MyTrait 为什么MyClass和MyClass2的初始化顺序有所不同? MyClass的构造函数将是 MyClass() { MyTr
请看下面的代码.

trait MyTrait { val myVal : String }

class MyClass extends MyTrait { val myVal = "Value" }

class MyClass2(val myVal: String) extends MyTrait

为什么MyClass和MyClass2的初始化顺序有所不同?
MyClass的构造函数将是

MyClass() {
  MyTrait$class.$init$(this);
  myVal = value
}

MyClass2的构造函数将是

MyClass2(String myVal) { this.myVal = myVal; MyTrait$class.$init$(this) }

我认为初始化顺序应该像MyClass2的构造函数一样,对于这两种情况都是一样的.

解决方法

在 Scala specification第5.1节的末尾,定义如下:

Template Evaluation. Consider a template sc with mt 1 with mt
n {stats}
. If this is the template of
a trait (§5.3.3) then its
mixin-evaluation consists of an eval-
uation of the statement sequence
stats. If this is not a template of a
trait,then its evaluation consists of
the following steps.

  • First,the superclass constructor sc is evaluated (§5.1.1).
  • Then,all base classes in the template’s linearization (§5.1.2) up
    to the template’s superclass denoted
    by sc are mixin-evaluated.
    Mixin-evaluation hap- pens in reverse
    order of occurrence in the
    linearization.
  • Finally the statement sequence stats is evaluated.

但是请注意,构造函数参数可能由随后的任何构造函数使用.因此,需要在它们之前进行初始化.这在第5.1.1节的末尾是明确的:

An evaluation of a constructor
invocation x.c targs. .
.(argsn)
consists of the following
steps:

  • First,the prefix x is evaluated.
  • Then,the arguments args1,. . .,argsn are evaluated from left to
    right.
  • Finally,the class being constructed is initialized by evaluating the
    template of the class referred to by
    c.

这没有任何问题,但是您最后执行的{stats}确实存在问题.最后执行{stats}的原因是它可以引用其祖先类和特征的属性,而祖先显然不了解其后代.因此,在执行{stats}之前,祖先需要完全初始化.

当然,您可能需要提前初始化. 5.1.6:早期定义涵盖了这一点.这是你如何写它:

class MyClass extends { val myVal = "Value" } with MyTrait

(编辑:李大同)

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

    推荐文章
      热点阅读