Wednesday, August 12, 2009

Properties

In scala all vars are properties. When compiled to bytecode each var is instead compiled to a getter and a setter (but not a java bean style getter and setter). You generate bean style getters and setters if you add the BeanProperty annotation (that is for another day).

The signature of the generated methods of an Int variable called property are:
  1. def property:Int
  2. def property_=( newVal:Int):Unit

Because of this you can declare the property as a var and in the future if you decide that you need behaviour in a setter and getter you can introduce those two methods in place of the single var and no client code is broken.
  1. scala>class C1( var property:Int )
  2. defined class C1
  3. scala>class C2( dependency:C1 ){
  4.      | println(dependency.property)
  5.      | dependency.property += 1
  6.      | println(dependency.property)
  7.      | }
  8. defined class C2
  9. scala>new C2(new C1(10))
  10. 10
  11. 11
  12. res0: C2 = C2@72e28a61
  13. scala>  class C1( privatevar p:Int) {
  14.      | def property = p
  15.      | def property_=(newVal:Int) = p = newVal * 100
  16.      | }
  17. defined class C1
  18. scala>  class C2( dependency:C1 ){
  19.      | println(dependency.property)
  20.      | dependency.property += 1
  21.      | println(dependency.property)
  22.      | }
  23. defined class C2
  24. scala>new C2(new C1(10))
  25. 10
  26. 1100
  27. res0: C2 = C2@62c639ce

Notice C2 uses the same API to access C1.property.

No comments:

Post a Comment