How to clone a Case Class instance and change just one field in Scala?

Using the copy function that case classes offer, you may clone an instance of a case class in Scala and modify a single field. You may create a new instance of a case class with updated fields while maintaining the integrity of the other fields by using the copy method that case classes automatically produce.

Utilizing the Copy Method

Scala case classes have a useful method called copy that generates a new instance of the case class with a few updated fields. Below is the Scala program to implement the above approach:

Scala
// Define a case class
case class Person(name: String, age: Int)

// Create an instance of the case class
val person1 = Person("Alice", 30)

// Clone the instance and change just one field
val person2 = person1.copy(age = 35)

// Output
println("Original Person: " + person1)  
println("Modified Person: " + person2)  

In this example, the person1 instance’s copy method is used to create a new instance, person2, with the name field left unaltered and the age field set to 35.

Output: