Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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?

like image 293
M.Ahsen Taqi Avatar asked Jul 30 '15 10:07

M.Ahsen Taqi


1 Answers

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(_)
}
like image 58
mattinbits Avatar answered Nov 05 '22 06:11

mattinbits