Sunday, January 24, 2010

Applying scala to solving real world problems: Say bye bye to boring constructors and getters/setters

In Java, it is very common and boring to create constructors and getters/setters like:

public class Foo {
  private String x;
  private String y;

  public Foo(String x, String y) {
    this.x = x;
    this.y = y;
  }
  public String getX() {
    return x;
  }
  public String getY() {
    return y;
  }
  public void setX(String x) {
    this.x=x;
  }
  public void setY(String y) {
    this.y=y;
  }
}

Yes, Eclipse provides the "Generate constructor using fields" and "Generate getters and setters" commands to do that, but it is still very boring and requires work from us. In Scala, all this boring work is no longer required:

class Foo(x: String, y: String) {
}

Due to the closure support, x and y will be available to all methods inside the Foo class just like Java fields:

class Foo(x: String, y: String) {
  def someMethod {
    println(x+y)
  }
}

To create getters, use to the "val" keyword:

class Foo(val x: String, val y: String) {
  ...
}

The Scala compile will create a getter methods named "x" and "y" automatically. To create setters in addition to getters, use "var" instead of "val":

class Foo(var x: String, var y: String) {
  ...
}

Then the compiler will create setter methods named "x =" and "y =" for you (Yes, the method name contains a space and then an equal sign, which are allowed in Scala). To call the getters and setters, you may:

val f = new Foo("a", "b")
f.x            //In Scala you don't need to use () to call a method
f.x = ("c")  //This is OK
f.x = "c"    //Again, don't have to use ()

Pretty neat, isn't it?