Fields (val or var) in scala class can get a getter (val) or setter/getter (var) automatically.
See this sample:
scala> class Person {
| var age = 0
| }
class Person
scala> tt.age
val res16: Int = 0
scala> tt.age=21
// mutated tt.age
scala> tt.age
val res17: Int = 21
And we can also customize the setter/getter methods.
scala> class Person {
| private var privateAge = 0
| def age = privateAge
| def age_=(newValue:Int) = {
| if (newValue > privateAge) privateAge = newValue
| }
| }
class Person
scala> val fred = new Person
val fred: Person = Person@c56c25b
scala> fred.age
val res21: Int = 0
scala> fred.age=30
// mutated fred.age
scala> fred.age=21
// mutated fred.age
scala> fred.age
val res22: Int = 30
This looks a bit different from ruby meta programming.
Return to home | Generated on 10/11/22