Guilherme Silveira Guilherme Silveira - 1 year ago 95
Scala Question

How can I create a read-only class member in Scala?

I want to create a Scala class where one of its var is read-only from outside the class, but still a var. How can I do it?

If it was a val, there was no need to do anything. By default, the definition implies public access and read-only.

Answer Source

Define a public "getter" to a private 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

res0: Int = 0

scala> foo.incBar()

res2: Int = 1

scala> = 4
<console>:7: error: value bar_= is not a member of Foo = 4
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download