Classes and properties

Kotlin · Essentials · 12 min

Classes model your domain; Kotlin removes the getter/setter/constructor boilerplate of Java.

A class with a primary constructor declares its properties in one line:

class Account(val owner: String, private var balance: Double = 0.0)

val/var in the constructor create properties; without them, parameters are only visible in initializers. Create instances without new: val acc = Account("Ada").

  • init { ... } blocks run during construction, in order with property initializers; use them for validation (require(balance >= 0)).
  • Secondary constructors (constructor(...) : this(...)) are rarely needed thanks to default arguments.
  • Properties have generated getters/setters; you access them like fields (acc.owner). Customize with accessors: val isEmpty get() = size == 0, or var name = "" set(value) { field = value.trim() }, where field is the backing field.
  • private set lets everyone read but only the class write.

Visibility: public (default), private, protected, and internal (visible within the same module). Classes are final by default: you must mark them open to allow inheritance.

Methods are functions inside the class and can access properties directly. toString, equals and hashCode come from Any and compare identity unless overridden; data classes (next lesson) generate them.

There is no static; use top-level functions or a companion object for class-level members.

Example

class Account(val owner: String, balance: Double = 0.0) {
    var balance = balance
        private set                     // readable outside, writable only inside

    val isEmpty: Boolean
        get() = balance == 0.0          // computed property

    init {
        require(owner.isNotBlank()) { "owner required" }
    }

    fun deposit(amount: Double) {
        require(amount > 0) { "amount must be positive" }
        balance += amount
    }
}

fun main() {
    val acc = Account("Ada")
    println(acc.isEmpty)                // true
    acc.deposit(50.0)
    println("${acc.owner}: ${acc.balance}") // Ada: 50.0
    // acc.balance = 1.0                // error: private setter
    runCatching { Account(" ") }.onFailure { println(it.message) } // owner required
}

Remember

  • Primary constructor val/var params become properties
  • init blocks validate; require() throws IllegalArgumentException
  • Custom get()/set() with field for the backing field
  • Classes are final unless marked open

Check yourself

  1. What does class P(name: String) (no val/var) give you?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kotlinlang.org/docs/classes.html