Kotlin essentials cheat sheet
Key ideas
valis a read-only reference, not a frozen object; avalholding aMutableListcan still change internally.- Smart casts work on local
val, parameters, and unchanged localvar; a classvarproperty needs a localvalcopy first. ==is structural equality (callsequals);===is reference equality. Use==in nearly all code.- Sealed types make
whenexhaustive; adding a sub-type forces everywhenwithoutelseto fail compilation until handled. let,apply,run,also,withare allinline;apply/alsoreturn the object,let/runreturn the lambda result.out Tis covariant (read-only),in Tis contravariant (write-only);MutableList<T>is invariant because it has bothget()andadd().lateinitthrowsUninitializedPropertyAccessExceptionif read early; test with::name.isInitialized; it does not work forInt,Boolean, or other primitives.- Platform types from Java (
String!) get no compile-time null checks unless annotated with@Nullable/@NonNull; declare the type yourself at the boundary. data classgeneratesequals(),hashCode(),toString(), andcopy()from primary-constructor properties only; body properties are ignored.- 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 term | Use it for |
|---|---|
val / var | read-only vs mutable reference; prefer val everywhere you can |
lateinit | deferred init for non-null, non-primitive properties; check with ::name.isInitialized |
lazy | thread-safe one-time init on first read for costly values that may never be needed |
sealed interface / sealed class | restrict sub-types to the same module and package for exhaustive when |
when | exhaustive branching over sealed types, enums, ranges; no else needed when exhaustive |
let / apply / run / also / with | scope functions for null checks, object config, and side-effects in pipelines |
out T / in T | covariant (return positions) and contravariant (parameter positions) variance on generics |
reified | enables is T and T::class inside inline generic functions; not callable from Java |
data class | auto-generates equals, hashCode, toString, copy from primary-constructor properties |
companion object | static-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 |
@JvmOverloads | generate 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 contravariantRules of thumb
- Prefer
?:withreturnorthrowfor early exit over nested null checks. - Never sprinkle
!!to silence the compiler; use?:,?., or fix the type instead. - Prefer
valin data classes used as UI state so every change goes throughcopy(). - Never add
elseto awhenover 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>toMutableListto add items; calltoMutableList()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
UninitializedPropertyAccessExceptionat runtime. Fix: make the property nullable or pass the value in through the constructor. - Treating List as immutable.
Listis a read-only view; if another reference holds theMutableList, changes are visible through yourList. Fix: calltoList()when you need a real snapshot. - Using apply when you need the lambda's return value.
applyalways returns the object, so the last expression inside the block is ignored. Fix: useletorrunwhen 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
Longor useBigDecimal. - 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(), ormap[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.