Let's say I have the following code:
class Pet(name: String) {
def getName: String = {
name match {
case "" => generateRandomName
case _ => name
}
}
}
object Pet {
def apply(name: String) = new Pet(name)
}
where creating a Pet with an empty name would create a Pet with a random name. How would I save the state of the newly generated random name, so calling this method twice would return the same name generated from the first call?
val pet = Pet("")
// Let's say this prints "bob"
println(pet.getName)
// I want this to still print "bob". This would generate a new random name because the state isn't saved from the previous call.
println(pet.getName)
I'd like to avoid var because it's considered bad practice -- how do you go about doing something like this? Is the best way to create a new copy of the class? That doesn't seem very efficient to me