Debugging
suggest changeDebugging 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:
- Line Breakpoint: Click the editor gutter next to a line of code (or press
Ctrl+F8/Cmd+F8). - Conditional Breakpoint: Right-click an existing breakpoint to specify a boolean Kotlin expression (for example,
userId == 42). Execution pauses only when the condition evaluates totrue. - Field Watchpoint: Click the gutter next to a property declaration to break when that property is read or written.
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:
- Open the Debug tool window.
- Select the Coroutines tab.
- 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
}
require(condition): Validates arguments; throwsIllegalArgumentException.check(condition): Validates internal state; throwsIllegalStateException.assert(condition): Standard JVM assertion enabled with the-eaflag.error(message): Unconditionally throwsIllegalStateException.