Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 134 ยท Idiomatic Kotlin

Kotlin Idioms

Learn idiomatic Kotlin: data classes, default arguments, expression bodies, null-handling patterns, collection operations, when, extensions and scope functions, with before-and-after code.

Every language has a way that experienced programmers write it, and Kotlin has a strong one. You can write Kotlin that compiles and works but reads like Java with different punctuation: getters and setters by hand, for loops with index counters, null checks nested five levels deep. Idiomatic Kotlin uses the language's own tools so the code is shorter, safer and easier to read. This lesson collects the patterns you will see in nearly every good Kotlin codebase, each shown as a "before" and an "after" so you can recognize both.

A word of caution first. Idioms are habits, not laws. The goal is clarity; if a one-liner needs a comment to be understood, a few plain lines are better. Each section below says when the idiom stops helping. The topics link to full lessons, so use this one as a map.

Use data classes for data

When a class exists to carry values, declare it as a data class. You get equals, hashCode, toString, copy and destructuring for free, and read-only val properties make the object safe to share.

Kotlin From boilerplate to one line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Prefer val over var everywhere you can. To "change" an immutable data class, make a modified copy with copy(...); the old value stays valid, which prevents a whole category of bugs.

Default and named arguments instead of overloads

In older style you write several overloads of a function, each calling the next one with a default. Kotlin lets you put the default right in the parameter list, and lets callers name the arguments they care about:

Kotlin One function, many call shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Named arguments also make calls with several booleans self-documenting: connect("x", secure = false) is far clearer than connect("x", 5432, false, 30). Note the trailing comma after the last parameter; it is allowed and makes diffs cleaner. See Default and Named Arguments.

Expressions instead of statements

In Kotlin, if, when and try all produce values. That removes the "declare a variable, then assign it in each branch" pattern. A function whose body is a single expression can be written with =:

Kotlin if, when and try as expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler checks that every branch of a when used as an expression is covered (an else, or all cases of an enum or sealed type). That is a guarantee you lose with the statement style. See if as an Expression and when Expressions.

Null safety patterns

Nulls are handled with a small, well-known toolkit. Compare the nested-check style with the idiomatic one:

Kotlin The null-handling toolkit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The chain ?. stops at the first null and ?: supplies a fallback. ?: return and ?: throw are the idiomatic guard clauses at the start of a function: after the line, the variable is non-null and the rest of the function is flat. What you should avoid is the non-null assertion !!, which simply converts the compiler's help into a run-time crash:

Kotlin !! turns a compile-time check into a crash (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program ends with Exception in thread "main" java.lang.NullPointerException and a stack trace pointing at the line. Use !! only in tests or where a null truly means a programming error, and then prefer requireNotNull(value) { "message" }, which explains what went wrong. See Null Safety.

Collection operations instead of loops

Most loops that build a new list, filter, count or group are better expressed with the collection functions, which say what you want rather than how:

Kotlin Loops versus collection operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This style also encourages you to read collections as immutable (List, not MutableList) and to build new ones. The cost: each step creates an intermediate list. For small lists that is irrelevant; for large pipelines use a sequence. A plain for loop is still right when the body has side effects, early exits or several variables to update. See Collection Transformations.

Extension functions: grow the vocabulary

Instead of utility classes full of static helpers, Kotlin programmers add extension functions to the types involved, so the call reads naturally:

Kotlin Extensions make intent visible

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Keep extensions small and put them near the code that needs them (or in a clearly named file). Do not extend types you do not own with function names that look like members and may clash later. See Extension Functions and Infix Functions and Operator Overloading.

Scope functions and builders for setup code

The scope functions apply, also, let, run, with shorten setup. The standard builders buildString and buildList remove the temporary mutable variable altogether:

Kotlin apply, buildString and buildList

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

apply returns the object itself, so it suits configuration. The mutable parts live only inside the builder; what you get back is typed as an ordinary read-only value. Do not nest scope functions three levels deep: when this and it from different levels start to mix, readability collapses.

Other idioms you will see daily

  • String templates instead of concatenation: "Hello, $name! You have ${items.size} items."
  • Single-expression functions: fun area(r: Double) = Math.PI * r * r.
  • Destructuring in for loops over maps: for ((key, value) in map).
  • in and ranges for checks: if (age in 18..65) instead of two comparisons.
  • lazy for expensive properties that are computed on first use.
  • use for anything closeable, so cleanup is guaranteed (Resources and use).
  • require and check for argument and state validation (require, check and assert).
  • Sealed types and when to model "one of these cases" (Sealed Classes and Interfaces).
  • object for singletons and companion object for factory functions, not static utility classes.
Kotlin lazy, in-ranges and object singletons together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

When an idiom hurts

The most common failure of "idiomatic" code is cleverness. A chain of eight operations with nested lambdas may impress, but a teammate has to decompose it to find a bug. Split such a chain with named intermediate vals, or extract a well-named function. Another is overusing nullability: if a value always exists, make it non-null and fix the data at the boundary instead of adding ?. everywhere. A third is reflexively adding inline, extension functions or custom operators: each is a tool for a specific problem, not a style requirement. When in doubt, imagine reading the code six months from now with no memory of writing it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which declaration gives you equals, hashCode, toString and copy without writing them?

    A data class generates these members from its primary constructor properties. A value class may only have one property and an object cannot take constructor parameters.
  2. 2. What does val customer = c ?: return "Hello, stranger" do?

    The elvis operator supplies the right-hand expression when the left side is null. Since return has type Nothing, the declared variable is non-null from then on.
  3. 3. Which is the idiomatic replacement for a chain of overloads with fewer parameters each?

    Defaults let one function cover all combinations, and named arguments make the call readable.
  4. 4. When is a plain for loop still a good choice over collection operations?

    Collection functions describe a transformation. When you mainly perform actions, break out early, or track more than one result, a loop is clearer.
  5. 5. Why should !! be avoided in application code?

    !! asserts non-null and throws if the value is null. Use ?., ?:, requireNotNull with a message, or restructure so the value cannot be null.

Summary

  • Use data classes for plain data, val over var, and copy to change immutable values.
  • Prefer default and named arguments to overload chains; use a trailing comma freely.
  • Treat if, when and try as expressions and use = bodies for one-expression functions.
  • Handle null with ?., ?:, ?: return, let and takeIf; avoid !!.
  • Use collection operations for transformations and loops for side effects and early exits.
  • Add extension functions for domain vocabulary; use apply, buildString and buildList for setup.
  • Reach for lazy, use, require, sealed types and object where they fit.
  • Stop when clarity suffers: readable code beats clever code.

Next: Type-Safe Builders and DSLs