Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 15 / Stage 3

Kotlin internals

Goal: See what kotlinc actually builds -- peek at the generated .class files with javap, understand properties as field-plus-accessor pairs, see why inline functions don't allocate a lambda object while ordinary ones do, and learn that delegated properties (by lazy, by Delegates.observable, your own by Logged(...)) and every operator (+, [], in, ()) are just ordinary function calls with a name the compiler looks for. Time: ~5 hours · Level: comfortable with Part 9's classes and Part 13's generics

🔍 Going deeper: everything below was compiled for real with kotlinc-jvm 2.4.21 (JRE 21.0.11+10-LTS) (see ../../TOOLING.md) and inspected with javap from that same JDK. Constant-pool numbers (#13, #61, ...) will differ if you compile the same file yourself -- that's just the order the compiler happened to intern things in, not something to memorize.

What you will learn

  • What kotlinc generates for a .kt file: a synthetic FileNameKt class holding every top-level function as a static method, and an ordinary JVM class for every class you write
  • Properties as bytecode: a backing field plus a getter (val) or getter+setter (var); a computed property with no field at all; why a class accesses its own field directly instead of going through its own getter/setter; lateinit's real failure mode
  • Why an ordinary lambda costs an allocated object (via invokedynamic) and an inline function call costs nothing -- the compiler pastes the lambda's body straight into the call site
  • noinline and crossinline: the two situations where a parameter of an inline function can't just be pasted in, and the exact compiler errors you get without them
  • Delegated properties (by ...): by lazy, Delegates.observable, Delegates.vetoable, a Map-backed property, and what the compiler actually generates for by -- a hidden xxx$delegate field plus calls to getValue/setValue
  • Operator conventions: +, *, >, [], in, () each resolve to one operator fun with a fixed name -- there is no other operator magic
  • Mini-build: your own delegate, Logged<T>, that reports every real change to a property

Topics in this part

Practice

Try each one yourself first. Then check the solution. Every exercise is one file with a top-level fun main(), using this part's properties/backing-field model, lambdas and inline functions, delegated properties, and operator conventions.


Exercise 1: A bank account's real shape

Scenario: A bank's account object needs a balance nobody outside the class can set directly, a computed loan-eligibility flag, and a branch code that's only known after the account is opened. What to do: Write class BankAccount(initialBalanceInr: Double) with var balanceInr (private setter), a computed val isEligibleForLoan (true when balanceInr >= 10_000.0), fun credit(amountInr: Double) and fun debit(amountInr: Double) that adjust the balance directly, and lateinit var branchIfsc: String. In main(): credit ₹8,000 and debit ₹1,000 from a ₹5,000 account, print the balance and loan eligibility, try reading branchIfsc before assigning it (catch the exception and print its simple class name), then assign and print it.

Sample output:

Balance: 12000.0
Eligible for loan: true
branchIfsc before assignment: UninitializedPropertyAccessException
branchIfsc after assignment: HDFC0001234

💡 Hint: credit/debit can write balanceInr += amountInr directly -- no need to call a setter yourself, even a private one, because code inside the class always touches the backing field directly (section 2).


Exercise 2: A UPI wallet with operator conventions

Scenario: A wallet app wants wallet["handle"], wallet["handle"] = amount, "handle" in wallet and wallet() for the grand total to just work, the same way a List or Map does. What to do: Write data class Balance(val paise: Long) : Comparable<Balance> with operator fun plus, operator fun minus, compareTo and a Rs.X.YY-style toString(). Write class Wallet wrapping a MutableMap<String, Balance> with operator fun get, set, contains and invoke() (the sum of every balance). In main(), put two UPI handles in a wallet, print one balance, check membership for a handle that isn't there and one that is, print the wallet total, subtract ₹25.00 from one handle using -, and compare two balances with >.

Sample output:

Rs.1500.00
false
true
Total across wallet: Rs.1825.00
ravi@upi after spend: Rs.300.00
asha richer than ravi: true

💡 Hint: wallet["ravi@upi"]!! - Balance(2500) calls your minus operator; write the result back with wallet["ravi@upi"] = ..., which calls your set operator.


Exercise 3: Prove by lazy only runs once

Scenario: A monthly sales report is expensive to build, and the team doesn't fully trust that by lazy really caches it -- they want proof, not a claim. What to do: Write class MonthlyReport with a private-set var computeCount: Int = 0 and val summary: String by lazy { computeCount++; "Total sales: Rs.48,500 across 3 cities" }. In main(), print computeCount before any access, read summary three times with repeat(3), then print computeCount again and a Boolean for "computed exactly once."

Sample output:

before any access, computeCount=0
Total sales: Rs.48,500 across 3 cities
Total sales: Rs.48,500 across 3 cities
Total sales: Rs.48,500 across 3 cities
computeCount after 3 reads: 1
computed exactly once: true

💡 Hint: computeCount++ inside the lazy { } block runs inside MonthlyReport's own scope, so it can touch the private-set property directly -- same rule as Exercise 1.


Exercise 4: Price history with observable and vetoable

Scenario: A shop's product price must never go negative, and every accepted change should be recorded for an audit log. What to do: Write class Product(val name: String) with a private history = mutableListOf<String>() and var priceInr: Int by Delegates.vetoable(0) { property, old, new -> ... }: when new < 0, return false (reject, no history entry); otherwise append "${property.name}: Rs.$old -> Rs.$new" to history and return true. Add fun priceHistory(): List<String>. In main(), set the price to 1200, then 1350, then try -500 (rejected), then 999; print the final price, every history entry, and whether the history has exactly 3 entries.

Sample output:

Final price: Rs.999
History:
  priceInr: Rs.0 -> Rs.1200
  priceInr: Rs.1200 -> Rs.1350
  priceInr: Rs.1350 -> Rs.999
History has 3 entries: true

💡 Hint: the history line is written inside the vetoable callback, only on the branch that returns true -- the rejected -500 attempt never reaches that line.


Exercise 5: User preferences from a Map, with sensible defaults

Scenario: A settings screen loads preferences from a config map that might not have every key -- a missing theme should fall back to "light", but a missing display name is a real error, not something to paper over. What to do: Write class UserPrefs(map: Map<String, Any?>) with val displayName: String by map (no default -- required), val theme: String by map.withDefault { "light" }, and val notificationsOn: Boolean by map.withDefault { true }. In main(), build one UserPrefs from a map with all three keys, and another from a map with only displayName; print both as one line each. Then build a UserPrefs from a map with no displayName and try to read it inside runCatching { }, printing the caught exception's simple class name.

Sample output:

Kavita Rao: theme=dark, notifications=false
Arjun Mehta: theme=light, notifications=true
missing displayName throws: NoSuchElementException

💡 Hint: by map (no withDefault) is the one that can throw -- by map.withDefault { ... } never does.


Exercise 6: Your own validated delegate

Scenario: A school's report card has marks and attendance that must always stay between 0 and 100, for any number of fields, without writing the same if check twice. What to do: Write a delegate class RangeChecked(low: Int, high: Int, initial: Int) with getValue/setValue that requires newValue in low..high, raising IllegalArgumentException with the message "<property name> must be in <low>..<high>, got <value>" otherwise. Write class ReportCard(studentMarks: Int, studentAttendance: Int) with var marks and var attendancePercent, both by RangeChecked(0, 100, ...). In main(), build a card, print both fields, raise marks to 95 and print it, try setting marks = 150 and attendancePercent = -5 inside runCatching { } (printing each caught message), then print whether marks is still 95.

Sample output:

marks=72, attendance=88
updated marks=95
marks=150 rejected: marks must be in 0..100, got 150
attendance=-5 rejected: attendancePercent must be in 0..100, got -5
marks unchanged after rejection: true

💡 Hint: property.name inside setValue is exactly what fills in marks vs attendancePercent in the message -- the same RangeChecked class works for both fields.


Exercise 7: noinline and crossinline, and the errors without them

Scenario: A batch order processor needs to validate each order inside a Runnable (so it can be swapped for a real task queue later), and keep one "all done" callback to call after the whole batch, not during it. What to do: Write inline fun <T> processOrders(orders: List<T>, noinline notifyAllDone: () -> Unit, crossinline isValid: (T) -> Boolean, action: (T) -> Unit). Inside: save notifyAllDone to a val before the loop (this is exactly why it must be noinline); for each order, set a var valid = false and run Runnable { valid = isValid(order) }.run() (this is exactly why isValid must be crossinline); call action(order) when valid; after the loop, call the saved callback. In main(), process five order ids where one is invalid, collecting the valid ones, and print the processed list and whether the bad one was skipped. Then, in a comment block, write the same function with both modifiers removed and paste the two exact compiler errors kotlinc gives for it.

Sample output:

batch finished
processed: [ORD-1, ORD-2, ORD-3, ORD-4]
skipped the bad order: true

💡 Hint: removing noinline fails exactly where the parameter is assigned to a val; removing crossinline fails exactly where the parameter is called inside Runnable { } -- the compiler points at the precise line both times.


Exercise 8: Reflection detective

Scenario: Before trusting this part's claims in your own code, prove them on a class you didn't just read about -- using reflection from inside the program itself, no javap needed. What to do: Write class Employee(initialSalaryInr: Double) with: var salaryInr (private setter), a computed val isWellPaid (>= 50_000.0), lateinit var department: String, val bonusInr: String by lazy { "computed bonus" }, and fun giveRaise(amountInr: Double). In main(), use Employee::class.java.declaredFields.map { it.name }.sorted() and .declaredMethods.map { it.name }.sorted().distinct() to print the field and method name lists, then print five Boolean lines answering: is there a public setSalaryInr? a public getSalaryInr? a backing field for isWellPaid? a backing field for department? a field whose name contains "delegate", for bonusInr?

Sample output:

Fields: [bonusInr$delegate, department, salaryInr]
Methods: [bonusInr_delegate$lambda$0, getBonusInr, getDepartment, getSalaryInr, giveRaise, isWellPaid, setDepartment]
has setSalaryInr (public setter): false
has getSalaryInr (public getter): true
has a backing field for isWellPaid: false
has a backing field for department (lateinit): true
has a $delegate field for bonusInr: true

💡 Hint: this is the same javap evidence from sections 2 and 4, just read through java.lang.Class reflection instead of the command line -- declaredFields/declaredMethods only list what's actually on this class, same as javap without inherited members.

Show the solutions for Part 15 (8 files)

solutions/ex01.kt

// Exercise 1 (green): a BankAccount with a private-set balance, a computed property, and a
// lateinit field that hasn't been assigned yet.

class BankAccount(initialBalanceInr: Double) {
    var balanceInr: Double = initialBalanceInr
        private set

    val isEligibleForLoan: Boolean
        get() = balanceInr >= 10_000.0

    lateinit var branchIfsc: String

    fun credit(amountInr: Double) {
        balanceInr += amountInr
    }

    fun debit(amountInr: Double) {
        balanceInr -= amountInr
    }
}

fun main() {
    val account = BankAccount(5000.0)
    account.credit(8000.0)
    account.debit(1000.0)
    println("Balance: ${account.balanceInr}")
    println("Eligible for loan: ${account.isEligibleForLoan}")

    val branchRead = runCatching { account.branchIfsc }.exceptionOrNull()
    println("branchIfsc before assignment: ${branchRead?.let { it::class.simpleName }}")

    account.branchIfsc = "HDFC0001234"
    println("branchIfsc after assignment: ${account.branchIfsc}")
}

solutions/ex02.kt

data class Balance(val paise: Long) : Comparable<Balance> {
    operator fun plus(other: Balance) = Balance(paise + other.paise)
    operator fun minus(other: Balance) = Balance(paise - other.paise)
    override fun compareTo(other: Balance) = paise.compareTo(other.paise)
    override fun toString() = "Rs.%d.%02d".format(paise / 100, paise % 100)
}

class Wallet(private val balances: MutableMap<String, Balance> = mutableMapOf()) {
    operator fun get(upiHandle: String): Balance? = balances[upiHandle]
    operator fun set(upiHandle: String, balance: Balance) { balances[upiHandle] = balance }
    operator fun contains(upiHandle: String) = upiHandle in balances
    operator fun invoke(): Balance = balances.values.fold(Balance(0)) { total, b -> total + b }
}

fun main() {
    val wallet = Wallet()
    wallet["asha@upi"] = Balance(150000)
    wallet["ravi@upi"] = Balance(32500)

    println(wallet["asha@upi"])
    println("meera@upi" in wallet)
    println("asha@upi" in wallet)
    println("Total across wallet: ${wallet()}")

    val afterSpend = wallet["ravi@upi"]!! - Balance(2500)
    wallet["ravi@upi"] = afterSpend
    println("ravi@upi after spend: ${wallet["ravi@upi"]}")
    println("asha richer than ravi: ${wallet["asha@upi"]!! > wallet["ravi@upi"]!!}")
}

solutions/ex03.kt

class MonthlyReport {
    var computeCount = 0
        private set

    val summary: String by lazy {
        computeCount++
        "Total sales: Rs.48,500 across 3 cities"
    }
}

fun main() {
    val report = MonthlyReport()
    println("before any access, computeCount=${report.computeCount}")
    repeat(3) {
        println(report.summary)
    }
    println("computeCount after 3 reads: ${report.computeCount}")
    println("computed exactly once: ${report.computeCount == 1}")
}

solutions/ex04.kt

import kotlin.properties.Delegates

class Product(val name: String) {
    private val history = mutableListOf<String>()

    var priceInr: Int by Delegates.vetoable(0) { property, old, new ->
        if (new < 0) {
            false
        } else {
            history += "${property.name}: Rs.$old -> Rs.$new"
            true
        }
    }

    fun priceHistory(): List<String> = history.toList()
}

fun main() {
    val product = Product("Pressure Cooker")
    product.priceInr = 1200
    product.priceInr = 1350
    product.priceInr = -500       // vetoed: no history entry, price unchanged
    product.priceInr = 999

    println("Final price: Rs.${product.priceInr}")
    println("History:")
    product.priceHistory().forEach { println("  $it") }
    println("History has 3 entries: ${product.priceHistory().size == 3}")
}

solutions/ex05.kt

class UserPrefs(map: Map<String, Any?>) {
    val displayName: String by map
    val theme: String by map.withDefault { "light" }
    val notificationsOn: Boolean by map.withDefault { true }
}

fun main() {
    val fullConfig = mapOf("displayName" to "Kavita Rao", "theme" to "dark", "notificationsOn" to false)
    val partialConfig = mapOf("displayName" to "Arjun Mehta")

    val full = UserPrefs(fullConfig)
    println("${full.displayName}: theme=${full.theme}, notifications=${full.notificationsOn}")

    val partial = UserPrefs(partialConfig)
    println("${partial.displayName}: theme=${partial.theme}, notifications=${partial.notificationsOn}")

    val missingRequired = runCatching { UserPrefs(mapOf("theme" to "dark")).displayName }.exceptionOrNull()
    println("missing displayName throws: ${missingRequired?.let { it::class.simpleName }}")
}

solutions/ex06.kt

import kotlin.reflect.KProperty

class RangeChecked(private val low: Int, private val high: Int, initial: Int) {
    private var value = initial

    operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = value

    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: Int) {
        require(newValue in low..high) { "${property.name} must be in $low..$high, got $newValue" }
        value = newValue
    }
}

class ReportCard(studentMarks: Int, studentAttendance: Int) {
    var marks: Int by RangeChecked(0, 100, studentMarks)
    var attendancePercent: Int by RangeChecked(0, 100, studentAttendance)
}

fun main() {
    val card = ReportCard(studentMarks = 72, studentAttendance = 88)
    println("marks=${card.marks}, attendance=${card.attendancePercent}")

    card.marks = 95
    println("updated marks=${card.marks}")

    val rejected = runCatching { card.marks = 150 }.exceptionOrNull()
    println("marks=150 rejected: ${rejected?.message}")

    val rejectedAttendance = runCatching { card.attendancePercent = -5 }.exceptionOrNull()
    println("attendance=-5 rejected: ${rejectedAttendance?.message}")

    println("marks unchanged after rejection: ${card.marks == 95}")
}

solutions/ex07.kt

inline fun <T> processOrders(
    orders: List<T>,
    noinline notifyAllDone: () -> Unit,
    crossinline isValid: (T) -> Boolean,
    action: (T) -> Unit
) {
    val runWhenDone = notifyAllDone          // only legal because notifyAllDone is `noinline`
    for (order in orders) {
        var valid = false
        Runnable { valid = isValid(order) }.run()   // only legal because isValid is `crossinline`
        if (valid) action(order)
    }
    runWhenDone()
}

fun main() {
    val orderIds = listOf("ORD-1", "ORD-2", "ORD-3", "ORD-BAD", "ORD-4")
    val processed = mutableListOf<String>()

    processOrders(
        orders = orderIds,
        notifyAllDone = { println("batch finished") },
        isValid = { id -> id != "ORD-BAD" },
        action = { id -> processed += id }
    )

    println("processed: $processed")
    println("skipped the bad order: ${"ORD-BAD" !in processed}")
}

// Same function with both modifiers removed, and the exact errors kotlinc gives for it:
//
// inline fun <T> processOrdersBroken(
//     orders: List<T>,
//     notifyAllDone: () -> Unit,
//     isValid: (T) -> Boolean,
//     action: (T) -> Unit
// ) {
//     val runWhenDone = notifyAllDone
//     for (order in orders) {
//         var valid = false
//         Runnable { valid = isValid(order) }.run()
//         if (valid) action(order)
//     }
//     runWhenDone()
// }
//
// ex07fail.kt:7:23: error: illegal usage of inline parameter 'notifyAllDone: () -> Unit'.
// Add 'noinline' modifier to the parameter declaration.
//     val runWhenDone = notifyAllDone
//                       ^^^^^^^^^^^^^
// ex07fail.kt:10:28: error: cannot inline 'isValid: (T) -> Boolean' here: it might contain
// non-local returns. Add 'crossinline' modifier to parameter declaration 'isValid: (T) ->
// Boolean'.
//         Runnable { valid = isValid(order) }.run()
//                            ^^^^^^^

solutions/ex08.kt

class Employee(initialSalaryInr: Double) {
    var salaryInr: Double = initialSalaryInr
        private set

    val isWellPaid: Boolean
        get() = salaryInr >= 50_000.0

    lateinit var department: String

    val bonusInr: String by lazy { "computed bonus" }

    fun giveRaise(amountInr: Double) {
        salaryInr += amountInr
    }
}

fun main() {
    val fields = Employee::class.java.declaredFields.map { it.name }.sorted()
    val methods = Employee::class.java.declaredMethods.map { it.name }.sorted().distinct()

    println("Fields: $fields")
    println("Methods: $methods")

    println("has setSalaryInr (public setter): ${"setSalaryInr" in methods}")
    println("has getSalaryInr (public getter): ${"getSalaryInr" in methods}")
    println("has a backing field for isWellPaid: ${"isWellPaid" in fields}")
    println("has a backing field for department (lateinit): ${"department" in fields}")
    println("has a \$delegate field for bonusInr: ${fields.any { it.contains("delegate") }}")
}

Common mistakes

Mistake Why it is wrong Fix
Expecting a private set setter to still exist in bytecode The compiler doesn't generate accessor methods nothing calls -- javap simply won't list setBalanceInr Don't rely on reflection to find a setter that was never generated; read the field through the public getter instead
Assuming a class calls its own getter/setter internally Kotlin accesses the backing field directly inside the declaring class -- a breakpoint on the setter won't catch an internal balanceInr += x Put logic that must run on every write (validation, logging) in a custom setter body (set(value) { ... }), not in a separate method that happens to assign the field
Treating lateinit var as "like val but later" It's a var with no null-safety net: reading before assignment throws UninitializedPropertyAccessException, and it can't be val or a primitive type Use lateinit only for reference types set once during setup (DI, test fixtures); use a nullable type or by lazy otherwise
Expecting inline to always help Inlining a large function body into every call site bloats the generated bytecode; the win is real only when a lambda parameter was actually being allocated Reserve inline for small functions that take lambdas, and for functions that need reified -- not for inlining for its own sake
Forgetting noinline/crossinline and guessing at the fix The compiler error names the exact missing modifier, but it's easy to add the wrong one noinline: the parameter is stored, returned, or passed elsewhere. crossinline: the parameter is called from inside another lambda/object, but never needs a non-local return
Writing a delegate with the wrong getValue/setValue signature by fails to compile with a delegate-mismatch error, often confusing for a first attempt Match the exact signature: operator fun getValue(thisRef: Any?, property: KProperty<*>): T, and setValue with an extra newValue: T parameter
Assuming Delegates.observable's callback runs only on a real change It fires on every assignment, even setting the same value again Use Delegates.vetoable or a custom delegate (like Logged) if "only when it actually changed" matters

Quick recap

  • kotlinc turns top-level functions into static methods on a synthetic FileNameKt class, and every class into an ordinary, final-by-default JVM class.
  • A property is a backing field plus accessor methods; a class accesses its own field directly, not through its own getter/setter; a computed property has no backing field at all.
  • An ordinary lambda allocates a FunctionN object via invokedynamic; inline pastes the lambda's body into the call site instead, which is also why reified needs inline.
  • noinline keeps a parameter as a real function value; crossinline allows it inside a nested lambda while blocking non-local return through it.
  • by delegate compiles to a hidden xxx$delegate field plus getValue/setValue calls; by lazy, Delegates.observable/vetoable, map-backed properties, and your own delegate are all the same mechanism underneath.
  • Every operator (+, [], in, (), >) is a plain call to an operator fun with a fixed name -- plus, get/set, contains, invoke, compareTo.

Checklist

  • I compiled a class and used javap -p to see its generated fields and methods myself.
  • I showed that a class accesses its own property's backing field directly, not through a getter/setter, by reading javap -c output for a method that touches the field.
  • I triggered UninitializedPropertyAccessException from an unread lateinit var.
  • I compared javap -c output for an inline and a non-inline call and found the invokedynamic/invokestatic pair versus the pasted-in instructions.
  • I removed noinline/crossinline from a parameter and reproduced both compiler errors.
  • I wrote by lazy, Delegates.observable, and a map-backed property myself.
  • I wrote my own delegate with getValue/setValue and used it with by.
  • I wrote at least one operator fun (get, set, contains, or invoke) on a class of my own and used the matching Kotlin syntax to call it.

Search the guide