Data Class in Kotlin

Level 3110 keystrokes

Defines a data class, which automatically gets toString, equals, hashCode and copy.

Kotlin code

// data class generates toString, equals, hashCode and copy from the constructor properties
1data class User(val name: String, val age: Int)
2
// Create an instance; the arguments fill name and age in order
3val user = User("Alice", 25)
// The generated toString prints User(name=Alice, age=25)
4println(user)
// Read the name property directly: prints Alice
5println(user.name)

Output

User(name=Alice, age=25)
Alice
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.

  • (× 4
  • )× 4
  • ,× 2
  • :× 2
  • "× 2
  • .× 1
  • =× 1

More Kotlin examples at level 3

← Kotlin typing practice