问题
I'm looking at Scala traits, but have yet to program in it, making this a hypothetical question.
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, Matthew
回答1:
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
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.
来源:https://stackoverflow.com/questions/18539829/can-scala-traits-have-vars-not-just-vals