Reputation: 481
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
Upvotes: 1
Views: 42
Reputation: 51271
Using a default value in the constructor, you can do something like this...
class Pet(name: String = generateRandomName) {
def getName: String = name
}
Then when you do this...
val pet = new Pet()
...getName
will always return the same generated name, but this...
val pet = new Pet("")
...will populate name
as an empty String
.
Upvotes: 3