KotlinPrintable

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.

Back to the Kotlin tutorial

Basics

SyntaxWhat it doesLesson
fun main() { println("Hi") }Program entry pointIntroduction
val x = 1 / var y = 2Read-only / changeable variableVariables
val n: Int = "42".toInt()Explicit type, conversionVariables
const val MAX = 10Compile-time constant (top level)Variables
7 / 2 7 % 2 7.0 / 2Integer division, remainder, decimal divisionNumbers & Operators
"%.2f".format(x)Format decimalsNumbers & Operators
(1..6).random()Random numberNumbers & Operators

Strings & null safety

SyntaxWhat it doesLesson
"Hi $name, ${a + b}"String templateStrings
s.trim() s.uppercase() s.replace("a", "b")Common string functionsStrings
s.split(",") list.joinToString(", ")Split and joinStrings
"""text""".trimIndent()Multi-line raw stringStrings
var s: String? = nullNullable typeNull Safety
s?.length ?: 0Safe call and Elvis defaultNull Safety
s?.let { use(it) }Run only when not nullNull Safety

Control flow & functions

SyntaxWhat it doesLesson
val x = if (c) a else bif as an expressionif & when
when (n) { 1, 2 -> ...; in 3..9 -> ...; else -> ... }when with values and rangesif & when
for (i in 1..5) 0 until n 10 downTo 0 step 2Loops and rangesLoops & Ranges
repeat(3) { }Run a block n timesLoops & Ranges
fun area(w: Double, h: Double) = w * hSingle-expression functionFunctions
fun f(a: Int, b: String = "x") then f(1, b = "y")Default and named argumentsFunctions

Collections & lambdas

SyntaxWhat it doesLesson
listOf(1, 2) / mutableListOf<Int>()Read-only / mutable listLists
mapOf("a" to 1) map["a"] ?: 0Map and safe lookupMaps & Sets
setOf(1, 2) a union b a intersect bSets and set operationsMaps & Sets
list.filter { it > 0 }.map { it * 2 }Filter and transformCollection Operations
list.sumOf { it.price } list.groupBy { it.type }Sum and groupCollection Operations
val f: (Int) -> Int = { it * 2 }Lambda with a function typeLambdas
list.filter(::isValid)Function referenceLambdas

Classes & types

SyntaxWhat it doesLesson
class User(val name: String, var age: Int = 0)Class with propertiesClasses & Objects
init { require(age >= 0) }Validate on creationClasses & Objects
data class Point(val x: Int, val y: Int)Data classData Classes
p.copy(y = 5) val (x, y) = pCopy and destructureData Classes
open class A class B : A() override fun f()InheritanceInheritance & Interfaces
interface Payable { fun pay(): Boolean }InterfaceInheritance & Interfaces
object Settings { } companion object { }Singleton and class-level membersObjects & Companions
enum class Size { S, M, L }Enum classEnums & Sealed Classes
sealed interface State { data object Loading : State }Sealed hierarchyEnums & Sealed Classes

Advanced Kotlin

SyntaxWhat it doesLesson
try { } catch (e: Exception) { } finally { }Handle exceptionsExceptions
runCatching { risky() }.getOrElse { 0 }Result-based error handlingExceptions
fun String.isEmail(): Boolean = ...Extension functionExtension Functions
fun <T : Comparable<T>> max(a: T, b: T)Generic function with a boundGenerics
obj.apply { } x?.let { } y.also { }Scope functionsScope Functions
suspend fun load() launch { } async { }.await()CoroutinesCoroutines
withContext(Dispatchers.IO) { }Switch dispatcherCoroutines
flow { emit(1) }.map { }.collect { }FlowFlows
MutableStateFlow(0) .value = 1Observable stateFlows
File("a.txt").readText() useLines { }Read filesFiles & I/O
@Test fun totalIsZero() { assertEquals(0, x) }Unit testTesting

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