Can Scala traits have vars, not just vals? [closed]

我的梦境 提交于 2019-12-11 14:49:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!