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

I have a Person class

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

I want to write a copy() method for my class, which can work just like a copy method, with case classes (copy and update an attribute of an object)

I know that copy() comes with the case class, but I do not use it, so I want the same for my class

please call me how can i do this?

+7
scala
source share
1 answer

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(_) } 
+9
source share

All Articles