Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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), 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 for us. Here is the byte-level code...