Classes, Properties & Data Classes
Primary constructors, properties with custom getters and setters, init blocks, and data classes.
Kotlin classes declare their constructor in the header and their fields as properties, removing the boilerplate of Java getters and setters. Data classes generate equals, hashCode, toString and copy for classes that just hold data.
A sensor class and a data class
class Sensor(val name: String, ...) declares the constructor and properties at once.
private set: lastValue is readable from outside but can only be changed inside the class.
init runs at construction; require throws IllegalArgumentException with the message when the condition fails.
span is a computed property with a custom getter.
data class Reading: == compares contents, === compares identity; copy() changes selected fields; destructuring reads components.
class Reading(val sensor: String, val value: Double) // then using it as a map key or in == data class Reading(val sensor: String, val value: Double)
A plain class compares by identity, so two readings with the same values are not equal. Data classes compare by content.
What does a data class generate?
equals/hashCode based on the primary-constructor properties, toString, copy(), and componentN() functions for destructuring.