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
data class TrailLegprints itself readably with no extra code.copy(km = 9.7)clones with one field changed; equality is by value.val (start, end, distance) = reroutedunpacks the properties in order.
Keywords and builtins used here
DoubleStringTrailLegclassdatafunmainval
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.
Step 1 of 3 in Classes & objects, step 13 of 27 in Language basics.