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
) http://bit.ly/djQVfm
The "setter" methods I don't know what to call are updateStrength
, updateWisdom
... but I will probably change that to withStrength
soon..