Friday, December 2, 2016

Getter & Setter methods of a 'var' in Class

#398
scala> class Math {
     |     // Note : = _ is called a zero value #400
     |     private[this] var mk:Int = _
     |
     |     // Getter method
     |     def mark:Int = {
     |         println("Retrieving value...")
     |         mk
     |     }
     |
     |     // Setter Method
     |     // **Note : ends with _=
     |     def mark_=(x: Int) = {
     |         println("Setting up value ")
     |         mk = x
     |     }
     | }
defined class Math

scala>

scala> val res = new Math()
res: Math = $iwC$$iwC$Math@1d38ca2b

scala> res.mark
Retrieving value...
res6: Int = 0

scala> res.mark = 8
Setting up value
Retrieving value...
res.mark: Int = 8