Just create a copy method that includes as parameters all the fields from the class definition, but which uses the existing values as default parameters, and 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(_) }
mattinbits
source share