简体   繁体   English

为什么在这种情况下val工作但在构造函数中没有var(scala)

[英]why val work but var doesn't in constructor in this case (scala)

I asked the following question if a variable is defined in a class extends a trait, how to use it in the trait? 我问了以下问题, 是否在类中定义了变量扩展了特征,如何在特征中使用它?

And one of the answer is as below: 答案之一如下:

trait T1 { def a: String; def x = a.length }
class Test(val a: String) extends T1

But if only works: 但是,如果只工作:

  1. define a in T1 as "def a", if I use "val a" or "var a", then it doesn't work 在T1中将a定义为“ def a”,如果我使用“ val a”或“ var a”,则它不起作用
  2. define a in Test as "val a", if I just use "a" which means default to "var a", it also doesn't work. 在Test中将a定义为“ val a”,如果我只使用“ a”,这意味着默认为“ var a”,那么它也不起作用。

Why does it happen? 为什么会发生?

"#1" should work, as I mentioned in the comment. 正如我在评论中提到的,“#1”应该有效。 Regarding #2, there two things: 关于#2,有两件事:

  1. class Test(a: String) is not the same as class Test(var a: String) (if anything, it is actually closer to val declaration, but isn't the same either, except for case classes). class Test(a: String) class Test(var a: String)不同的(如果有的话,它实际上更接近val声明,但是除了大小写类之外也不相同)。 The latter declares a as a mutable class member, while the former just makes it an argument to the constructor, not a member of the class at all. 后者a a声明为可变的类成员,而前者只是将其作为构造函数的参数,而不是该类的成员。 For this reason, it fails in your case: you have to override the abstract member a of T1 in order to be able to extend it. 因此,在您的情况下它将失败:您必须重写T1的抽象成员a才能对其进行扩展。

  2. class Test(var a: String) won't work either. class Test(var a: String)也不起作用。 This is because a is declared in T1 as def , which makes it immutable. 这是因为aT1声明为def ,这使其不可变。 You can override a def with a def or a val , but you cannot override it with a mutable value. 您可以使用defval覆盖def ,但不能使用可变值覆盖def If you need it to be mutable in Test , you have to declare it as a var in T1 as well. 如果需要它在Test是可变的,则还必须在T1中将其声明为var

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM