The copy method
When using a data class, you get a copy
 method out of the box. This method allows you to create a new instance of your type while cherry-picking the fields you want to change. For example, you may decide that you want to get a new BlogEntry
instance from an existing instance of which you just want to change the title and description fields
:
blogEntry.copy(title = "Properties in Kotlin", description = "Properties are awesome in Kotlin")
If you are familiar with Java, you will notice a similarity with the clone method. However, the copy method is more powerful; it allows you to change any of the fields in your new copied instance.
If you look at the parameter information of the copy method (CTRL+Â PÂ is the default keyboard shortcut), you should see the following:
Copy method parameters
In the screenshot, you can see that each field is contained within []
, thus marking it optional. To make this work, the compiler generates two methods...