Kotlin Cheat Sheet
Variables, strings, null safety, when, loops, functions, collections, lambdas, classes, sealed types, extensions, scope functions, coroutines, flows and tests on one printable page.
Strings & null safety
| Syntax | What it does | Lesson |
|---|
"Hi $name, ${a + b}" | String template | Strings |
s.trim() s.uppercase() s.replace("a", "b") | Common string functions | Strings |
s.split(",") list.joinToString(", ") | Split and join | Strings |
"""text""".trimIndent() | Multi-line raw string | Strings |
var s: String? = null | Nullable type | Null Safety |
s?.length ?: 0 | Safe call and Elvis default | Null Safety |
s?.let { use(it) } | Run only when not null | Null Safety |
Control flow & functions
| Syntax | What it does | Lesson |
|---|
val x = if (c) a else b | if as an expression | if & when |
when (n) { 1, 2 -> ...; in 3..9 -> ...; else -> ... } | when with values and ranges | if & when |
for (i in 1..5) 0 until n 10 downTo 0 step 2 | Loops and ranges | Loops & Ranges |
repeat(3) { } | Run a block n times | Loops & Ranges |
fun area(w: Double, h: Double) = w * h | Single-expression function | Functions |
fun f(a: Int, b: String = "x") then f(1, b = "y") | Default and named arguments | Functions |
Collections & lambdas
| Syntax | What it does | Lesson |
|---|
listOf(1, 2) / mutableListOf<Int>() | Read-only / mutable list | Lists |
mapOf("a" to 1) map["a"] ?: 0 | Map and safe lookup | Maps & Sets |
setOf(1, 2) a union b a intersect b | Sets and set operations | Maps & Sets |
list.filter { it > 0 }.map { it * 2 } | Filter and transform | Collection Operations |
list.sumOf { it.price } list.groupBy { it.type } | Sum and group | Collection Operations |
val f: (Int) -> Int = { it * 2 } | Lambda with a function type | Lambdas |
list.filter(::isValid) | Function reference | Lambdas |
Advanced Kotlin
| Syntax | What it does | Lesson |
|---|
try { } catch (e: Exception) { } finally { } | Handle exceptions | Exceptions |
runCatching { risky() }.getOrElse { 0 } | Result-based error handling | Exceptions |
fun String.isEmail(): Boolean = ... | Extension function | Extension Functions |
fun <T : Comparable<T>> max(a: T, b: T) | Generic function with a bound | Generics |
obj.apply { } x?.let { } y.also { } | Scope functions | Scope Functions |
suspend fun load() launch { } async { }.await() | Coroutines | Coroutines |
withContext(Dispatchers.IO) { } | Switch dispatcher | Coroutines |
flow { emit(1) }.map { }.collect { } | Flow | Flows |
MutableStateFlow(0) .value = 1 | Observable state | Flows |
File("a.txt").readText() useLines { } | Read files | Files & I/O |
@Test fun totalIsZero() { assertEquals(0, x) } | Unit test | Testing |
How to use this Kotlin cheat sheet
This Kotlin cheat sheet collects the syntax you'll reach for most often, in the same order as the course: program structure, variables and types, strings, null safety, conditions and loops, functions, collections and lambdas, classes, data and sealed classes, extensions, generics, scope functions, coroutines, files and tests. Each row links to the lesson that explains it with examples and common mistakes.
Keep it open while you practise. When you can't remember whether it's until or ..<, how let differs from apply, or how to start a coroutine, a quick look here is faster than a search. Type part of a keyword into the filter box to jump straight to it, or print the page and keep it beside your keyboard.
Kotlin gotchas worth remembering
- val is not deeply immutable.
val list = mutableListOf(1) can't be reassigned, but list.add(2) still works. Use listOf when the contents shouldn't change. - !! defeats null safety. It throws a NullPointerException when the value is null. Prefer
?., the Elvis operator ?: or let, and keep !! for cases you can prove. - when needs every case as an expression. When you use
when to return a value, the compiler insists on an else branch, unless you're matching every case of an enum or sealed class. - == compares values, === compares references. Unlike Java,
== on strings checks their contents, which is almost always what you want. - Ranges include the end.
1..5 contains 5. Use 1 until 5 or 1..<5 to stop before it, which is handy for list indexes. - Data classes only use the primary constructor. Properties declared in the class body aren't part of
equals, hashCode, toString or copy. - Scope functions return different things.
apply and also return the object; let, run and with return the lambda result. Mixing them up leads to surprising types. - Coroutines need a scope.
launch and async only work inside a CoroutineScope, and runBlocking is meant for main functions and tests, not app code.
A quick revision routine
Paste one section into the Kotlin Playground or a scratch file in IntelliJ each day and change one thing at a time. Then try the Kotlin quiz to see which ideas have stuck.
The Kotlin lessons behind this cheat sheet