I have a class Person
class Person(val name: String, val height : Int, val weight: Int)
I want to write copy()
method for my class that can work same as the copy method does with case classes(copy and update the attribute of the object)
I know copy()
comes with case class but i am not using them so i want the same thing for my class
please guide me how can i do this?
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(_)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With