I do not know what to call my "setters" on immutable objects?
For a mutable object Person, setters work like this:
class Person(private var _name: String) {
def name = "Mr " + _name
def name_=(newName: String) {
_name = newName
}
}
val p = new Person("Olle")
println("Hi "+ p.name)
p.name = "Pelle"
println("Hi "+ p.name)
This is all well and good, but what if Person is immutable?
class Person(private val _name: String) {
def name = "Mr " + _name
def whatHereName(newName: String): Person = new Person(newName)
}
val p = new Person("Olle")
println("Hi "+ p.name)
val p2 = p.whatHereName("Pelle")
println("Hi "+ p2.name)
What should whatHereName
be called?
EDIT: I need to put stuff in the "setter" method, like this:
class Person(private val _name: String) {
def name = "Mr " + _name
def whatHereName(newName: String): Person = {
if(name.length > 3)
new Person(newName.capitalize)
else
throw new Exception("Invalid new name")
}
}
The real code is much bigger than this, so a simple call to the copy
method will not do.
EDIT 2:
Since there are so many comments on my faked example (that it is incorrect) I better give you the link to the real class (Avatar
).
The "setter" methods I don't know what to call are updateStrength
, updateWisdom
... but I will probably change that to withStrength
soon..
Setter methods are usually used to change the state of the object and, since the goal of an immutable class is to avoid state changes, we do not provide any setter methods.
An object whose state cannot change after it has been constructed is called immutable (unchangable). The methods of an immutable object do not modify the state of the object. In Scala, all number types, strings, and tuples are immutable. The classes Point, Date, Student, and Card we defined above are all immutable.
Immutable objects and data structures are first-class citizens in Scala. This is because they prevent mistakes in distributed systems and provide thread-safe data.
I like the jodatime way. that would be withName.
val p = new Person("Olle")
val p2 = p.withName("kalle");
more jodatime examples: http://joda-time.sourceforge.net/
Scala case classes have autogenerated method copy for this purpose. It's used like this:
val p2 = p.copy(name = "Pelle")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With