如何在Scala中创建只读类成员?

Gui*_*ira 18 variables scala member

我想创建一个Scala类,其中一个var是从类外部读取的,但仍然是var.我该怎么做?

如果是val,则无需做任何事情.默认情况下,该定义意味着公共访问和只读.

mis*_*tor 36

为私人定义公共"getter" var.

scala> class Foo {
     |   private var _bar = 0
     |
     |   def incBar() { 
     |     _bar += 1 
     |   }
     |
     |   def bar = _bar
     | }
defined class Foo

scala> val foo = new Foo
foo: Foo = Foo@1ff83a9

scala> foo.bar
res0: Int = 0

scala> foo.incBar()

scala> foo.bar
res2: Int = 1

scala> foo.bar = 4
<console>:7: error: value bar_= is not a member of Foo
       foo.bar = 4
           ^
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。不幸的是,这是唯一的解决方案:(它很烂,因为var真实名称正因如此而变脏。比暴露我的胆量要好。谢谢 (2认同)