I could not find a natural way to do something like that in scala :
class Car {
var speed: Int
var color: String
}
var myCar = new Car()
myCar.set {
speed = 5
color = "green"
}
I know it is possible in other languages as Groovy. I also know I can do it with a constructor like this :
val myCar = new Car {
speed = 5
color = "green"
}
I am interested in a way to do the same, not at the object construction but later, once the object has already been created
This is what I have been doing so far :
class Car (var speed: Int, var color: String) {
def set(f: (Car) => Unit) = {
f(this)
}
}
val myCar = new Car(5, "red")
myCar.set { c =>
c.speed = 12
c.color = "green"
}
But I do not like the need to write the 'c' var for every attribute
Any idea on how I can do it or if there is an easier way ??