A Scala case class copy method example

Scala case class FAQ: When you create a case class in Scala, a copy method is generated for your case class. What does this copy method do?

In short, it lets you make a copy of an object, where a "copy" is different than a clone, because with a copy you can change fields as desired during the copying process.

To demonstrate this, let's create an Employee class as a case class:

scala> case class Employee(name: String, office: String, role: String)
defined class Employee

Next, we'll create an instance of an Employee named fred:

scala> val fred = Employee("Fred", "Anchorage", "Salesman")
fred: Employee = Employee(Fred,Anchorage,Salesman)

Finally, we'll call the copy method on fred to create a new employee named joe who has the same characteristics as the employee named fred, but with a different name:

scala> val joe = fred.copy(name="Joe")
joe: Employee = Employee(Joe,Anchorage,Salesman)

As you can see, joe is a copy of fred, but with a different name, which we changed during the copy process.

If you ever need to make a copy of an object in Scala, but not a clone, this gives you a little example of how the auto-generated copy method on a Scala case class works.

Post new comment

The content of this field is kept private and will not be shown publicly.