copy method in Scala is used to copy an instance of an object or
case class. The copy obtained, however, is different from the original, as you can tweak fields to match the copy required. This is also known as making a shallow copy since the values aren’t copied from the object, but the references to object fields are.
copy method requires fields of the
case class to be defined for the new copy you want to generate.
copy method returns a copy of an instance of an object without cloning it completely.
Below is an example of how you can use the
copy method. Firstly, we create a
case class Employee that stores the name, age, and salary of the employees. Then, we create an instance of the first employee who’s named
Samia. We want to copy Samia’s data for another employee who is the same
age and earns the same
salary, but has a different name. Hence, we use the
copy method to copy
employee1 with a change in the
case class Employee(name: String, age: Int, salary: Int) val employee1 = Employee("Samia Ishaque", 23, 4500) val employee2 = employee1.copy(name="Ali") print(employee1.name +"\n") print(employee2.name)
View all Courses