← Back to Kotlin Course | Chapter 14: JVM Interop & Best Practices | Lesson 6 of 7

Writing Idiomatic Kotlin

Idiomatic Kotlin means writing code the way experienced Kotlin developers naturally would, using the language's own shortcuts instead of old habits from other languages.

Preferring Expressions Over Statements

Idiomatic Kotlin favors expression-based constructs -- if/when as expressions, single-expression functions -- over verbose statement-based equivalents copied from other languages.

Example: Preferring Expressions Over Statements

markup
fun describe(n: Int) = when {
    n < 0 -> "negative"
    n == 0 -> "zero"
    else -> "positive"
}

// Entry point: execution of the program starts here
fun main() {
    // Print `describe(-5)` to the console, with a trailing newline
    println(describe(-5))
    // Print `describe(0)` to the console, with a trailing newline
    println(describe(0))
    // Print `describe(10)` to the console, with a trailing newline
    println(describe(10))
}

Using Data Classes Instead of Manual Boilerplate

Reaching for data class instead of manually writing equals(), hashCode(), and toString() is a hallmark of idiomatic Kotlin, saving both code and potential bugs.

Example: Using Data Classes Instead of Manual Boilerplate

markup
// Define a data class `Point`
data class Point(val x: Int, val y: Int)

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `p1`, set to `Point(1, 2)`
    val p1 = Point(1, 2)
    // Declare a read-only variable `p2`, set to `Point(1, 2)`
    val p2 = Point(1, 2)
    // Print "Equal: ${p1 == p2}, toString: $p1" to the console, with a trailing newline
    println("Equal: ${p1 == p2}, toString: $p1")
}

Embracing Null Safety Idioms

Idiomatic Kotlin uses ?., ?:, and safe scope functions instead of manual null checks copied from languages without built-in null safety.

Example: Embracing Null Safety Idioms

markup
// Define the function `greetOrDefault` taking `name` and returning a String
fun greetOrDefault(name: String?): String = name?.let { "Hello, $it!" } ?: "Hello, stranger!"

// Entry point: execution of the program starts here
fun main() {
    // Print `greetOrDefault("Kotlin")` to the console, with a trailing newline
    println(greetOrDefault("Kotlin"))
    // Print `greetOrDefault(null)` to the console, with a trailing newline
    println(greetOrDefault(null))
}

Favoring Immutability and Small Functions

Idiomatic Kotlin leans toward val over var, read-only collections over mutable ones by default, and small, well-named functions (including extensions) over large, do-everything utility classes.

Example: Favoring Immutability and Small Functions

markup
fun List<Int>.average2(): Double = if (isEmpty()) 0.0 else sum().toDouble() / size

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `scores`, set to `listOf(80, 90, 70)`
    val scores = listOf(80, 90, 70)
    // Print "Average: ${scores.average2()}" to the console, with a trailing newline
    println("Average: ${scores.average2()}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing Java-style code in Kotlin, such as manual getter/setter methods or verbose null checks, instead of using Kotlin's built-in properties and null-safety operators.
  2. Ignoring expression-oriented features like if/when as expressions and single-expression functions, resulting in unnecessarily verbose code.
  3. Overusing advanced features (like heavy operator overloading or excessive DSLs) where plain, simple code would be clearer.
Chapter Summary
  • Prefer val over var, expression bodies over verbose blocks, and built-in null-safety operators over manual null checks.
  • Use data classes for simple data holders instead of manually writing equals/hashCode/toString.
  • Favor immutable collections and small, focused extension functions over sprawling utility classes.
  • Idiomatic code favors clarity and conciseness together, not brevity at the expense of readability.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.