Copying data classes in Kotlin

Level 4237 keystrokes

copy() creates a new data class object with the same values, except the properties you pass as named arguments. The original stays unchanged, which suits immutable (val) properties.

Kotlin code

// A data class gets copy(), toString(), equals() and more generated automatically
1data class User(val name: String, val age: Int, val active: Boolean)
2
// The original object
3val user1 = User("Alice", 25, true)
// New object with only age changed; user1 is not modified
4val user2 = user1.copy(age = 26)
// Several properties can be changed at once; age stays 25
5val user3 = user1.copy(name = "Bob", active = false)
6
// Print User(name=Alice, age=25, active=true), unchanged
7println(user1)
// Print User(name=Alice, age=26, active=true)
8println(user2)
// Print User(name=Bob, age=25, active=false)
9println(user3)

Output

User(name=Alice, age=25, active=true)
User(name=Alice, age=26, active=true)
User(name=Bob, age=25, active=false)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 7
  • )× 7
  • =× 6
  • ,× 5
  • "× 4
  • :× 3
  • .× 2

More Kotlin examples at level 4

← Kotlin typing practice