18

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

36

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

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
           ^
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
  • 2
    Thanks. Unfortunately this is the only solution :( It sucks because the var real name gets dirty just because of that. Better than exposing my guts. Thanks – Guilherme Silveira Jun 02 '11 at 14:46
1

Define a trait with the "getter" method:

trait Foo { def bar: T }

Define a class which extends this trait, and which has your variable

private class FooImpl (var bar: T) extends Foo

Restrict the visibility of this class appropriately.

Having a dedicated interface allows you also to use multiple implementation classes at runtime, e.g. to cover special cases more efficiently, lazy loading etc.