Scala trait 可以有 vars,而不仅仅是 vals 吗? [英] Can Scala traits have vars, not just vals?
问题描述
我正在研究 Scala 特征,但尚未对其进行编程,因此这是一个假设性问题.
I'm looking at Scala traits, but have yet to program in it, making this a hypothetical question.
到目前为止,我看到的所有示例都有具体或抽象的字段,它们仅在声明中使用 val
而不是 var
.使用 var
声明的字段可以在 Scala trait 中使用吗?
All of the examples that I've seen so far have concrete or abstract fields that only use val
in their declaration instead of var
. Can fields declared with var
be used in Scala traits?
TIA,马修
推荐答案
如果你尝试你会看到它有效:
If you try it you'll see it works:
scala> trait TestTrait {
| var x = 1
| }
defined trait TestTrait
scala> val t = new TestTrait { }
t: TestTrait = $anon$1@4c32060c
scala> t.x = 2
t.x: Int = 2
scala> t.x
res0: Int = 2
如果您了解 var
和 val
在 Scala 中是如何编译的,这是有道理的.val
是具有自动生成的 getter 方法的私有字段,而 var
的唯一区别是它也有一个 setter.
If you read into how var
and val
are compiled in Scala this makes sense. A val
is a private field with an auto-generated getter method, and the only difference for a var
is that is has a setter as well.
这篇关于Scala trait 可以有 vars,而不仅仅是 vals 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!