Kotlin essentials cheat sheet

Revise Kotlin essentials: null safety, smart casts, sealed classes, when, scope functions, generics variance, and data classes for Android interviews.

Key ideas

  1. val is a read-only reference, not a frozen object; a val holding a MutableList can still change internally.
  2. Smart casts work on local val, parameters, and unchanged local var; a class var property needs a local val copy first.
  3. == is structural equality (calls equals); === is reference equality. Use == in nearly all code.
  4. Sealed types make when exhaustive; adding a sub-type forces every when without else to fail compilation until handled.
  5. let, apply, run, also, with are all inline; apply/also return the object, let/run return the lambda result.
  6. out T is covariant (read-only), in T is contravariant (write-only); MutableList<T> is invariant because it has both get() and add().
  7. lateinit throws UninitializedPropertyAccessException if read early; test with ::name.isInitialized; it does not work for Int, Boolean, or other primitives.
  8. Platform types from Java (String!) get no compile-time null checks unless annotated with @Nullable/@NonNull; declare the type yourself at the boundary.
  9. data class generates equals(), hashCode(), toString(), and copy() from primary-constructor properties only; body properties are ignored.
  10. Sequences are lazy: intermediate steps do nothing until a terminal call (toList, first, sum). Use them for large lists with early exit, not for small lists.

APIs at a glance

API or termUse it for
val / varread-only vs mutable reference; prefer val everywhere you can
lateinitdeferred init for non-null, non-primitive properties; check with ::name.isInitialized
lazythread-safe one-time init on first read for costly values that may never be needed
sealed interface / sealed classrestrict sub-types to the same module and package for exhaustive when
whenexhaustive branching over sealed types, enums, ranges; no else needed when exhaustive
let / apply / run / also / withscope functions for null checks, object config, and side-effects in pipelines
out T / in Tcovariant (return positions) and contravariant (parameter positions) variance on generics
reifiedenables is T and T::class inside inline generic functions; not callable from Java
data classauto-generates equals, hashCode, toString, copy from primary-constructor properties
companion objectstatic-like members on a class; from Java needs Companion. unless @JvmStatic
asSequence()convert a collection to a lazy sequence for large lists with early exit
@JvmOverloadsgenerate Java overloads for default arguments; required on custom View constructors used from XML

Snippets

Sealed interface with exhaustive when

sealed interface UiState {
    data object Loading : UiState
    data class Success(val items: List<String>) : UiState
    data class Error(val message: String) : UiState
}
 
fun render(state: UiState): String = when (state) {
    UiState.Loading -> "Loading..."
    is UiState.Success -> "Items: " + state.items.joinToString(", ")
    is UiState.Error -> "Error: " + state.message
}

Scope functions: null-safe parse and side-effect logging

fun parsePort(raw: String?): Int {
    return raw?.let {
        val trimmed = it.trim()
        val port = trimmed.toIntOrNull()
        if (port == null || port !in 1..65535) -1 else port
    } ?: -1
}
 
fun loadAndLog(data: List<String>): List<String> {
    return data.also {
        println("Loaded " + it.size + " items")
    }.filter { it.isNotBlank() }
}

Generics variance: covariant producer, contravariant consumer

interface Producer<out T> {
    fun produce(): T
}
 
interface Consumer<in T> {
    fun consume(item: T)
}
 
val strings: Producer<String> = object : Producer<String> {
    override fun produce() = "json"
}
val anyProducer: Producer<Any> = strings // ok: out T is covariant
 
val anyConsumer: Consumer<Any> = object : Consumer<Any> {
    override fun consume(item: Any) = println(item)
}
val stringConsumer: Consumer<String> = anyConsumer // ok: in T is contravariant

Rules of thumb

  • Prefer ?: with return or throw for early exit over nested null checks.
  • Never sprinkle !! to silence the compiler; use ?:, ?., or fix the type instead.
  • Prefer val in data classes used as UI state so every change goes through copy().
  • Never add else to a when over a sealed type; let the compiler enforce exhaustiveness.
  • Prefer == over === for all value comparisons; === gives surprising results on numbers and strings.
  • Never cast List<T> to MutableList to add items; call toMutableList() for a mutable copy.

Gotchas

  • Using lateinit for convenience. If you cannot say who sets it before first use, a read at the wrong time throws UninitializedPropertyAccessException at runtime. Fix: make the property nullable or pass the value in through the constructor.
  • Treating List as immutable. List is a read-only view; if another reference holds the MutableList, changes are visible through your List. Fix: call toList() when you need a real snapshot.
  • Using apply when you need the lambda's return value. apply always returns the object, so the last expression inside the block is ignored. Fix: use let or run when you need the computed result.
  • Capturing an Activity or View in a long-lived lambda. Singletons, callbacks, and static fields keep the Activity alive, causing a memory leak. Fix: clear the callback on destroy or use a weak reference.
  • Storing money in Double. Rounding errors appear with floating-point arithmetic. Fix: store whole cents in a Long or use BigDecimal.
  • Calling first(), single(), or getValue() on data that may be missing. They throw on an empty list or a missing key. Fix: use firstOrNull(), singleOrNull(), or map[key] when empty is a normal case.

Quick interview answers

What is the difference between val and var?

val is a read-only reference; you cannot reassign it, but the object it points to may still be mutable (for example a MutableList). var allows reassignment. Prefer val everywhere you can, and expose List instead of MutableList to callers.

When does a smart cast fail in Kotlin?

A smart cast fails when the compiler cannot prove the value cannot change between the check and the use. A class var property is the common case because another thread or call could mutate it; copy it to a local val first so the compiler can guarantee stability.

What is the difference between apply and also?

Both return the receiver object, but apply passes the object as this (you write bare property names) while also passes it as it (you write it.property). Use apply to configure a mutable object and also for logging or validation side-effects that should not change the pipeline type.

What does out T mean in a generic declaration?

out T marks the type parameter as covariant: T appears only in return positions, so List<out E> is a read-only producer. You can read elements but cannot call add(). MutableList<T> is invariant because it has both get(): T and add(T).

Why use a sealed class or sealed interface with when?

A sealed type restricts sub-types to the same module and package, so the compiler can check that every when branch is handled. If you add a new sub-type later, every when without else fails to compile until you add a branch, which is the safety guarantee.

What is a platform type and how do you handle it?

A platform type (for example String!) comes from unannotated Java code where Kotlin cannot tell if the value is null. Annotations like @Nullable and @NonNull turn it into a real Kotlin type; without them there is no compile-time null check. Declare the type yourself at the Java-to-Kotlin boundary.

Go deeper