1
data class Person(val age: Int, val name: String)

Is there a simple way to create a new Person object using another object as a template to fill in the required constructor params?

// Example of what I'd like to be able to do

val person1 = Person(age = 35, name = "Cory")

val person2 = Person(person1, name = "Jeff")

2 Answers 2

2

You can use copy() method, available in data classes, and override parameters you want to change:

val person1 = Person(age = 35, name = "Cory")
val person2 = person1.copy(name = "Jeff")

https://kotlinlang.org/docs/reference/data-classes.html#copying

Sign up to request clarification or add additional context in comments.

Comments

2

Every data class in Kotlin has a copy function:

val person2 = person1.copy(name = "Jeff") // but its age is still 35 (from Cory)

All parameters are optional in the copy function, so you can overwrite / change the ones you like.

Note that the copy() call performs a shallow copy

See: Data Class Copying

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.