[英]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: 但是,如果只工作:
Why does it happen? 为什么会发生?
"#1" should work, as I mentioned in the comment. 正如我在评论中提到的,“#1”应该有效。 Regarding #2, there two things:
关于#2,有两件事:
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
才能对其进行扩展。
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. 这是因为
a
在T1
声明为def
,这使其不可变。 You can override a def
with a def
or a val
, but you cannot override it with a mutable value. 您可以使用
def
或val
覆盖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.