1

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.