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 (CTRLP is the default keyboard shortcut), ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.