How to write copy() method for Simple Class in Scala

Using same names for parameters in copy method would make it similar to the copy method in case classes.

class Person(val name: String, val height: Int, val weight: Int) {
  def copy(
      name: String = this.name,
      height: Int = this.height,
      weight: Int = this.weight,
  ) = new Person(name, height, weight)
}

The copy method can be used as following.

val john = new Person("John", 89, 160)
val joe = john.copy(name = "Joe")

Just create a copy method which includes as parameters all the fields from the class definition, but which uses the existing values as default parameters, then create a new instance using all the parameters:

class Person(val name: String, val height : Int, val weight: Int) {

  def copy(newName: String = name, newHeight: Int = height, newWeight: Int = weight): Person = 
    new Person(newName, newHeight, newWeight)

  override def toString = s"Name: $name Height: $height Weight: $weight"
}

val person = new Person("bob", 183, 85)

val heavy_person = person.copy(newWeight = 120)

val different_person = person.copy(newName = "frank")

List(person, heavy_person, different_person) foreach {
  println(_)
}

Tags:

Scala