Classes in Kotlin

From the Kotlin cheat sheet · Classes & Objects · verified Jul 2026

Classes

Class declarations and constructors

kotlin
// Primary constructor
class Person(val name: String, var age: Int)

// Full syntax with init block
class Student(firstName: String, lastName: String) {
    val fullName: String
    var grade: Int = 0

    init {
        fullName = "$firstName $lastName"
        println("Student created: $fullName")
    }

    // Secondary constructor
    constructor(name: String) : this(name, "") {
        println("Secondary constructor called")
    }
}

// Properties with getters/setters
class Temperature {
    var celsius: Double = 0.0
        get() = field
        set(value) {
            field = if (value < -273.15) -273.15 else value
        }

    val fahrenheit: Double
        get() = celsius * 9/5 + 32
}
💡 Primary constructor is part of class header
⚡ init blocks run during instance initialization
📌 Use field keyword to access backing field in setters
🟢 Class delegation with by keyword promotes composition

More Kotlin tasks

Back to the full Kotlin cheat sheet