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

初始化具有特征的匿名类

发布时间:2020-12-16 09:39:13 所属栏目:安全 来源:网络整理
导读:有人可以帮助我了解以下行为吗? 简单地说:以下两种情况之间有什么区别? 我定义一个简单的类c特征 scala class c {val x=true; val y=this.x} defined class cscala trait t {}defined trait t 我可以实例化一个新的“c with t” scala new c with tres32:
有人可以帮助我了解以下行为吗?

简单地说:以下两种情况之间有什么区别?

我定义一个简单的类c特征

scala> class c {val x=true; val y=this.x} 
defined class c

scala> trait t {}
defined trait t

我可以实例化一个新的“c with t”

scala> new c with t
res32: c with t = $anon$1@604f1a67

但是我不能用t来实例化一个新的“匿名类c”

scala> new {val x=true; val y=this.x} with t
<console>:9: error: type mismatch;
 found   : type
 required: ?{def x: ?}
<console>:9: error: value x is not a member of object $iw
              new {val x=true; val y=this.x} with t

这两种情况有什么区别?

谢谢!

解决方法

你已经偶然发现了“早期定义”的语法( more info)。

查看语言规范的5.1.6部分:

An early definition is type-checked and evaluated in the scope which
is in effect just before the template being defined,augmented by any
type parameters of the enclosing class and by any early definitions
preceding the one being defined. In particular,any reference to this
in the right-hand side of an early definition refers to the identity
of this just outside the template. Consequently,it is impossible that
an early definition refers to the object being constructed by the
template,or refers to one of its fields and methods,except for any
other preceding early definition in the same section.

在你的情况下,问题在于this.x。如果你用x替换它,那么你所指的是前面最后一句提到的“先前的早期定义”(谢谢,@ som-snytt!),它编译。

当然,你可能并不打算写一个早期的初始化程序,所以只要按照Kristian Domagala的答案写下来。

(编辑:李大同)

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

    推荐文章
      热点阅读