Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 134 ยท Practice

Common Kotlin Mistakes

The Kotlin mistakes professionals see most: nullable calls, !!, platform types, shared mutable state, swallowed cancellation, equality traps and number pitfalls, each with a failing example and the fix.

Kotlin removes whole categories of bugs, but not all of them. Most of the mistakes that remain come from a handful of misunderstandings: what "read-only" really means, where Java's rules leak in, how == behaves, and what cancellation asks of your code. This lesson walks through the mistakes seen most often in code reviews. Each one is shown failing, with the real compiler or runtime message, and then fixed.

The order follows how often you will meet them: compile errors first (they are the friendly ones), then runtime surprises, then the subtle bugs that compile, run and quietly do the wrong thing.

Mistakes the compiler catches

The compiler is your first reviewer. Learn to read its messages, because each one points at a real rule. The program below contains three typical errors at once; Kotlin reports all of them in one go.

Kotlin Three common compile errors (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 three messages are:

TEXT
main.kt:3:17: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'.
main.kt:6:5: error: 'val' cannot be reassigned.
main.kt:10:13: error: operator '==' cannot be applied to 'Int' and 'Long'.
  1. Calling a member on a nullable value. String? might be null, so .length is not allowed. Handle the null case with ?., ?: or an if check; see Null Safety.
  2. Reassigning a val. Declare it var if it truly changes, but first ask whether you can compute a new value instead. See Variables.
  3. Comparing different number types. Kotlin never converts Int to Long silently, not even for ==. Convert one side explicitly. See Numbers.
Kotlin The three fixes

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.

Reaching for !! and trusting platform types

The !! operator says "I know this is not null; crash if I am wrong". It silences the compiler instead of answering its question. Real programs meet null in two ways: the value is genuinely missing (use ?: or an early return), or it came from Java.

Values returned by Java code have platform types, written String! in IDE hints. Kotlin cannot know if Java may return null, so it lets you treat the value as either String or String?. If you pick the non-null reading and the value is null, the crash happens at the first use, which may be far from the cause.

Kotlin Platform types hide a null

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 first line shows the fix: declare the type yourself (String?) whenever you store the result of a Java call that can be null, and the compiler guards every later use. The JDK message names the variable ("platform" is null), which is helpful, while a failed !! carries no message at all. See Java Interoperability.

Search your code for !!. Each one should have a reason you can state in a sentence ("the map is built from this enum, every key exists"). If you cannot, replace it with ?:, requireNotNull(x) { "message" } or a redesign of the type.

Shared mutable state and false immutability

List in Kotlin is a read-only view, not an immutable collection. If someone else holds the mutable object behind it, your "read-only" list changes under you. Returning a private mutable list through a read-only type is the classic leak.

Changing a collection while you loop over it is the other classic mistake: the iterator notices and throws.

Kotlin Read-only is a view, and loops dislike changes

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.

Defend against both: return a copy (toList()) or an unmodifiable wrapper when exposing internals, and use removeAll, filter or an explicit iterator() with remove() when removing during a loop. Across threads the problem is bigger. Two coroutines or threads that update the same var or MutableList race each other and lose updates; the fix is to confine the state to one thread, use an atomic or a Mutex, or share immutable data. See Shared Mutable State and Mutable Collections.

Equality traps

== calls equals and === compares identity. That much is simple, but a few corners surprise even experienced developers: arrays compare by identity, a data class holding an array inherits that, and floating-point numbers have two different equalities depending on whether the compiler knows the static type.

Kotlin Equality surprises

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.

Rules to remember:

  • Compare arrays with contentEquals (or use lists), and avoid arrays inside data classes; otherwise the generated equals compares references.
  • NaN == NaN is false when both sides are statically Double, but true when they are boxed as Any (because equals must be consistent with hashing). Use isNaN() to test for it.
  • Use == for values. Reserve === for the rare case where you really need identity. See Equality and Identity.

Coroutine mistakes: swallowed cancellation and leaks

Cancellation in coroutines works by throwing a CancellationException from the next suspension point. If your code catches Exception (or Throwable) around a suspending call and does not rethrow, you swallow the cancellation, and the coroutine goes on working although its parent has given up.

Kotlin Swallowing cancellation, and the fix

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 related leak is starting work in GlobalScope (or in a scope you never cancel). Such a coroutine belongs to nobody: errors are not reported to a parent, it outlives the screen or request that started it, and tests cannot wait for it. Start coroutines inside a scope you own, such as coroutineScope { } as above, or a service's own CoroutineScope that you cancel when the service stops. Also remember that a tight CPU loop never suspends and therefore never notices cancellation unless it checks isActive or calls ensureActive(). See Cancellation, Structured Concurrency and Coroutine Exceptions.

Numbers, initialization and empty collections

The last group compiles and often runs, which is why it is dangerous.

Kotlin Silent and loud number and state bugs

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.

  • Overflow wraps silently. Int.MAX_VALUE + 1 becomes the most negative Int. Use Long, Math.addExact (throws) or BigInteger when values can grow.
  • Integer division truncates. 1 / 2 is 0, so 1 / 2 * 100 is 0. Make one operand a Double.
  • Binary floating point is inexact. Never store money in Double; use BigDecimal or integer cents.
  • lateinit is a promise. Reading it too early throws. Prefer constructor parameters, a nullable type, or by lazy.
  • first() on an empty list throws. Use firstOrNull() when emptiness is normal. The same applies to max(), single() and get(index) versus getOrNull(index).
  • Integer division by zero throws; floating-point division gives infinity. Check divisors from user input.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a function returning List<String> still change after you received it?

    Read-only does not mean immutable. If a class returns its private MutableList as a List, callers see later changes. Return toList() to hand out a snapshot.
  2. 2. What is the best fix for an NPE caused by a platform type from Java code?

    An explicit nullable type makes the compiler check every use, so the missing value is handled where it enters your code.
  3. 3. What does Double.NaN == Double.NaN print when both sides are statically typed Double?

    IEEE 754 comparison says NaN is not equal to anything, including itself. Boxed as Any, equals is used and returns true. Use isNaN().
  4. 4. A coroutine wraps delay(1000) in catch (e: Exception) and does not rethrow. What is the effect of job.cancel()?

    CancellationException is an Exception. Catching it without rethrowing stops the cancellation from propagating, so the code after the try still runs.
  5. 5. What is 1 / 2 * 100 in Kotlin?

    1 / 2 is integer division and gives 0, and 0 * 100 is 0. Write 1.0 / 2 * 100 to get 50.0.

Summary

  • Read compiler messages: nullable receivers, val reassignment and mixed number types are rules, not nuisances.
  • Replace !! with ?:, requireNotNull or a better type; type Java results explicitly as nullable.
  • List is a view; return copies, and never modify a collection while iterating over it.
  • Share immutable data, or protect mutable state with confinement, atomics or a Mutex.
  • Compare arrays with contentEquals, avoid arrays in data classes, and test floats with isNaN() and tolerances.
  • Rethrow CancellationException, avoid GlobalScope, and start coroutines in a scope you own.
  • Watch for silent overflow, integer division, inexact doubles and lateinit reads, and prefer firstOrNull-style functions.

Next: Kotlin for Java Developers