A Kotlin class declares its constructor in its header. Parameters marked val or var in that header become properties - the field, the getter and, for var, the setter are all generated. This is why Kotlin classes are short: the ceremony that Java spreads over thirty lines is the parameter list.
Kotlin has no fields in the Java sense, only properties. When you write obj.name you are calling a getter, even though it reads like direct access. That matters because it means you can later replace a stored property with a computed one and no calling code changes - the syntax is identical either way.
A custom getter computes its value on each access and stores nothing. An init block runs during construction and is where validation belongs; throwing from it means an invalid object can never exist. For the common case of wanting a default that depends on other parameters, default arguments in the header usually beat a secondary constructor.
Visibility defaults to public, which is a deliberate reversal of Java's package-private default. The modifiers are public, internal (visible within the compilation module), protected and private.
class Device(val model: String, var osVersion: Int, private val serial: String) {
// A computed property: no storage, recalculated on each access
val isSupported: Boolean
get() = osVersion >= 26
// Validation during construction - an invalid Device cannot exist
init {
require(osVersion > 0) { "osVersion must be positive, was $osVersion" }
}
fun describe() = "$model on API $osVersion (supported: $isSupported)"
}
fun main() {
val phone = Device("Pixel 8", 34, "SN-001")
println(phone.describe())
phone.osVersion = 21 // var, so reassignable
println(phone.describe()) // isSupported recomputes to false
}
Discussion
No questions on this topic yet. Sign in to ask the first one.