Getters and Setters in Scala

2008-12-08 09:03:05

The inflexible, mutually exclusive relationship between Java methods and properties force programmers to make irreversible design decisions up front. Often the solution is to avoid exposing properties altogether, using getter and setter methods instead--leading to yet another addition to the amount of boilerplate to type and giving rise to other annoyances like the JavaBean concept.

Scala, on the other hand, has a better approach. Consider the following fairly useless class Foo in Scala:

class Foo {

  var mutableVar = "x"

}

Foo has one public property, mutableVar, which can be written to and read from with impunity. It is entirely exposed, hanging out there for the world to see.

Unlike Java however, you are not screwed when 3 months from now some new legislation requires that every read and write to mutableVar be counted. In Scala this is not a problem. Foo can be re-written as follows without affecting existing client code in any way whatsoever:

class Foo {
 
  private var reads = 0 
  private var writes = 0
  private var mv = "x"

  def mutableVar = {
    reads = reads + 1
    mv
  }

  def mutableVar_=(mv:String) = {
    writes = writes + 1
    this.mv = mv
  }

}

So the following client code would work just as well with the old version of Foo as the new:

val f = new Foo()
f.mutableVar = "xxx"
println(f.mutableVar) // prints "xxx"

Orator In Cheif
Mercurial and Nested Repositories (AKA Submodules)
Server Side Javscript, Usurper of PHP?
Master Your API
This Site is Hosted on EC2


up . rss .