SyntaxStudy
Sign Up
Kotlin Classes, Constructors and Properties
Kotlin Beginner 1 min read

Classes, Constructors and Properties

Kotlin classes are declared with the class keyword. The primary constructor appears directly in the class header, and constructor parameters prefixed with val or var are automatically promoted to properties, eliminating the need to write explicit field declarations and assignments. Secondary constructors are declared inside the class body with the constructor keyword and must delegate to the primary constructor using this(). Init blocks run as part of primary construction and are useful when property initialisation requires more than a simple assignment. Properties in Kotlin are more than just fields: each has a backing field and automatically generated getter and setter. You can customise either accessor to add validation or computed behaviour without changing the call-site syntax.
Example
// Primary constructor with properties
class Person(val name: String, var age: Int) {

    // Property with custom getter
    val isAdult: Boolean
        get() = age >= 18

    // Property with backing field and custom setter
    var email: String = ""
        set(value) {
            require(value.contains('@')) { "Invalid email: $value" }
            field = value   // 'field' refers to the backing field
        }

    // Init block — runs during construction
    init {
        require(name.isNotBlank()) { "Name must not be blank" }
        require(age >= 0)          { "Age must be non-negative" }
    }

    // Secondary constructor
    constructor(name: String) : this(name, 0)

    override fun toString() = "Person(name=$name, age=$age)"
}

// Sealed class hierarchy
sealed class Shape {
    abstract fun area(): Double
    class Circle(val radius: Double)            : Shape() { override fun area() = Math.PI * radius * radius }
    class Rectangle(val w: Double, val h: Double): Shape() { override fun area() = w * h }
}

fun main() {
    val alice = Person("Alice", 28)
    alice.email = "alice@example.com"
    println(alice)
    println("Adult: ${alice.isAdult}")

    val shapes: List<Shape> = listOf(Shape.Circle(5.0), Shape.Rectangle(3.0, 4.0))
    shapes.forEach { s ->
        val desc = when (s) {
            is Shape.Circle    -> "Circle  area=${s.area()}"
            is Shape.Rectangle -> "Rect    area=${s.area()}"
        }
        println(desc)
    }
}