Debugging

suggest change

Debugging Kotlin applications effectively involves using IDE breakpoint tools, coroutine diagnostics, and standard library inspection idioms.

Breakpoints in IntelliJ IDEA and Android Studio

The most common way to debug Kotlin is through the IntelliJ IDEA or Android Studio debugger:

Smart Step Into for Lambdas and Higher-Order Functions

Kotlin code frequently chains higher-order functions (such as map, filter, and let). When paused on a line containing multiple lambda expressions, pressing Step Into (F7) or Smart Step Into (Shift+F7) displays an inline popup allowing you to choose specifically which method or lambda body to enter.

Debugging Expression Chains with .also

When working with chained functional transformations, adding logging or inspecting intermediate values without breaking the chain is straightforward using .also:

fun processOrders(orders: List<Order>): List<String> {
    return orders
        .filter { it.total > 50.0 }
        .also { println("Filtered orders count: ${it.size}") }
        .map { it.customerEmail.lowercase() }
        .also { emails -> println("Recipient emails: $emails") }
}

Because .also returns its receiver object, it can be safely inserted anywhere in a fluent call chain without modifying return types or logic.

Debugging Coroutines

Asynchronous coroutines jump between threads, making standard thread stack traces difficult to interpret. Kotlin provides dedicated tools for debugging coroutines:

Coroutine Names in Logs

Pass a CoroutineName element in the coroutine context and enable coroutine debugging to include the coroutine name and ID in log output:

import kotlinx.coroutines.*

fun main() = runBlocking<Unit>(CoroutineName("MainRunner")) {
    launch(CoroutineName("DataLoader")) {
        println("Loading data on thread: ${Thread.currentThread().name}")
    }
}

Run the application with the -Dkotlinx.coroutines.debug JVM argument to include the coroutine name in thread names:

Loading data on thread: main @DataLoader#2

Coroutines Debugger Panel

When running under IntelliJ IDEA with coroutine debugging enabled:

  1. Open the Debug tool window.
  2. Select the Coroutines tab.
  3. Inspect all active, suspended, and running coroutines along with their current suspension stack traces and context variables.

Fail-Fast Checks and Assertions

Kotlin provides built-in validation functions that throw informative exceptions when invariants are violated:

fun withdraw(account: Account, amount: Double) {
    // Throws IllegalArgumentException if false
    require(amount > 0.0) { "Withdrawal amount must be positive, got $amount" }

    // Throws IllegalStateException if false
    check(account.balance >= amount) {
        "Insufficient funds: balance is ${account.balance}, requested $amount"
    }

    account.balance -= amount
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents