typestar

Data classes in Kotlin

One keyword buys equals, hashCode, toString, copy and destructuring.

// A data class writes equals, hashCode, toString and copy for you.
data class TrailLeg(val from: String, val to: String, val km: Double)

fun main() {
    val morning = TrailLeg("Aspen Gate", "Windy Col", 8.4)
    println(morning)

    // copy changes only what you name; the original is untouched.
    val rerouted = morning.copy(km = 9.7)
    println(rerouted == morning)

    val (start, end, distance) = rerouted
    println("$start to $end is $distance km")
}

How it works

  1. data class TrailLeg prints itself readably with no extra code.
  2. copy(km = 9.7) clones with one field changed; equality is by value.
  3. val (start, end, distance) = rerouted unpacks the properties in order.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
437
Tokens
88
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 1 of 3 in Classes & objects, step 13 of 27 in Language basics.

← Previous Next →