पाठ 7 / 25

Classes, Constructors and Properties

Primary constructors, init blocks and accessors.

Properties instead of fields

A class can declare a primary constructor in its header; prefixing parameters with val or var turns them into properties. init blocks run during construction and are a good place for validation with require. Properties have optional custom getters and setters; field refers to the backing field inside an accessor. Secondary constructors (constructor(...)) must delegate to the primary one. Classes are final by default, there is no new keyword, and lateinit var allows non-null properties that are initialised after construction (for example by dependency injection).

Model data with little boilerplate

Kotlin classes declare properties in the constructor; data, sealed and enum classes cover common modelling needs.

Three ideas: classes and properties, data classes, sealed hierarchies and enums.
Figure 3.1 — Class, data class and sealed hierarchy.

A class with validation and accessors

Properties live in the constructor.

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

    val isOverdrawn: Boolean
        get() = balance < 0                 // computed on every access

    init {
        require(owner.isNotBlank()) { "owner must not be blank" }
    }

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

fun main() {
    val acc = Account("Ada", initialBalance = 100)
    acc.deposit(50)
}

A form with built-in rules

The primary constructor is the form you fill in, init is the clerk who checks it, and properties with private setters are fields you can read but only the office can change.

त्वरित जाँच: What does `class Point(val x: Int, val y: Int)` declare?

  • A class with a primary constructor and two read-only properties
  • A function named Point
  • A data class with copy()
  • An open class that can be subclassed
Answer

A class with a primary constructor and two read-only properties — val in the constructor creates properties; classes are final by default.