Wednesday 14 February 2018

Kotlin: Data Classes: copy function

By default, Kotlin data class generate copy function. By using copy function, we can copy data object by altering some of its properties.

         var employee1 = Employee("Krishna", "Gurram", "India")
         var employee2 = employee1.copy(firstName = "Chamu")

Find the below working application.

Test.kt
package com.sample.test

data class Employee(var firstName: String, var lastName: String, var country: String)

fun main(args: Array<String>) {
 var employee1 = Employee("Krishna", "Gurram", "India")
 var employee2 = employee1.copy(firstName = "Chamu")

 println("employee1 : $employee1")
 println("employee2 : $employee2")
}

Output
employee1 : Employee(firstName=Krishna, lastName=Gurram, country=India)
employee2 : Employee(firstName=Chamu, lastName=Gurram, country=India)


Can I provide explicit implementation of copy function?
No, it is not allowed.




Previous                                                 Next                                                 Home

No comments:

Post a Comment