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


i have class person

class person(val name: string, val height : int, val weight: int) 

i want write copy() method class can work same copy method case classes(copy , update attribute of object)

i know copy() comes case class not using them want same thing class

please guide me how can this?

just create copy method includes parameters fields class definition, uses existing values default parameters, create new instance using 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(_) } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -