All cheatsheets

Cheatsheets

Kotlin

Null safety, data classes, lambdas, collections, scope functions, and coroutines.

Test yourself

81 entries

Variables & null safety9

val x = 1

Read-only (assign-once) — like Java final. Prefer val by default.

var y = 1

Mutable — reassignable. Use only when the value really changes.

val n: Int = 1

Explicit type; usually omitted thanks to type inference.

val s: String? = null

Nullable type — the `?` makes null a legal value; without it null won't compile.

a?.b?.c

Safe call — returns null instead of throwing if any link in the chain is null.

a ?: b

Elvis operator — supply a fallback when the left side is null.

a!!

Not-null assertion — force-unwrap; throws NPE if it actually is null.

lateinit var repo: Repo

Defer non-null init (DI/setUp); throws if read before assigned.

val x by lazy { compute() }

Lazy val — computed once on first access, then cached.

Functions8

fun add(a: Int, b: Int): Int { return a + b }

Standard function declaration.

fun add(a: Int, b: Int) = a + b

Expression body — `=` instead of `{}`; return type is inferred.

fun greet(name: String = "World")

Default arguments — callers may omit parameters that have defaults.

greet(name = "Kotlin")

Named arguments — pass by name for clarity and to skip middle defaults.

fun sum(vararg nums: Int): Int

Vararg — variable number of args; spread an array with `*arr`.

infix fun Int.times(s: String)

Infix call: `2 times "hi"` — single-param member/extension.

fun foo() { fun bar() {} }

Local function — nested, can capture the outer function's variables.

tailrec fun fact(n, acc)

tailrec — compiler rewrites a tail-recursive call into a loop (no stack overflow).

Lambdas & higher-order functions6

val f = { x: Int -> x * 2 }

Lambda literal stored in a val; type is (Int) -> Int.

fun apply(x: Int, op: (Int) -> Int) = op(x)

Higher-order function — takes (or returns) another function.

list.map { it.name }

Trailing-lambda syntax + implicit `it` — the dominant Kotlin idiom.

val ref = ::println

Function reference (`::name`); `Class::method` for member refs.

list.fold(0) { acc, x -> acc + x }

Lambda with multiple params — name them before `->`.

inline fun run(block: () -> Unit)

inline — lambda body is copied into the call site; no closure allocation.

Collections10

listOf(1, 2, 3)

Read-only List; mutableListOf(...) / ArrayList for a mutable one.

mapOf("a" to 1)

Read-only Map of pairs (`key to value`); mutableMapOf for mutable.

setOf(1, 2, 2)

Read-only Set (unique elements); mutableSetOf for mutable.

list.filter { }.map { }

Transform pipelines — filter/map/etc. return new collections, never mutate.

list.fold(0) { acc, x -> acc + x }

fold — collapse a collection to a single value with an accumulator.

list.groupBy { it.type }

Group into Map<K, List<V>> by a key selector.

list.associateBy { it.id }

Build Map<K, V> keyed by a selector (associateWith for value).

list.firstOrNull { it.ok }

Safe find — returns null instead of throwing when nothing matches.

list.sortedByDescending { it.score }

Return a sorted copy (sortedBy / sortedWith for comparators).

seq.asSequence()

Sequence — lazy, single-pass evaluation (Kotlin's Stream).

Control flow & when7

val x = if (a > b) a else b

`if` is an expression — it returns a value (no ternary needed).

when (x) { 1 -> "one"; else -> "?" }

when — a powerful switch that is also an expression.

for (i in 0..9) { }

Range loop, inclusive `..`; `until` (exclusive), `downTo`, `step 2`.

for ((k, v) in map) { }

Destructure entries while iterating a Map.

while (cond) { } / do { } while (cond)

Standard while / do-while loops.

loop@ for (x in xs) { break@loop }

Labels — break/continue an outer loop explicitly.

repeat(3) { i -> }

repeat(n) — run a block n times (inline stdlib function).

Classes, data & objects8

class User(val name: String, var age: Int)

Primary constructor in the header; `val`/`var` declare properties.

data class Point(val x: Int, val y: Int)

data class — auto equals/hashCode/toString/copy/componentN from the primary constructor.

object Singleton { fun work() {} }

object declaration — a lazily-initialised, thread-safe singleton.

companion object { fun create() }

Companion — class-level members; the Kotlin replacement for `static`.

object : Runnable { override fun run() {} }

Anonymous object — Kotlin's anonymous class / object expression.

enum class Color { RED, GREEN }

Enum class; entries can hold properties and override methods.

open class Base / class D : Base()

Classes are `final` by default — mark `open` to allow inheritance.

abstract class Shape { abstract fun area(): Double }

Abstract class with abstract members to override.

Sealed types & interfaces7

sealed interface Result<out T>

Sealed hierarchy — a closed set of subtypes known at compile time.

interface Repo { fun find(id: Int): User? }

Interface — may declare abstract members and default implementations.

fun save() { /* default */ }

Interface methods can have default bodies (no Java 8 needed).

val name: String // in interface

Interfaces can declare abstract properties (no backing field).

class A : Base(), Repo, Cloneable

Single class inheritance, multiple interface implementation.

data object Loading

data object — singleton variant with a nice toString (great in sealed types).

class C : Repo by impl

Interface delegation — forward all Repo calls to `impl` (composition over inheritance).

Smart casts & properties7

if (x is String) x.length

Smart cast — after an `is`/null check the compiler treats x as the narrowed type.

val s = x as String

Unsafe cast — throws ClassCastException if the type doesn't match.

val s = x as? String

Safe cast — returns null instead of throwing on mismatch.

var temp: Int = 0 get() set(v) { field = v }

Custom property accessors — `get()`/`set()`; `field` is the backing field.

const val MAX = 100

Compile-time constant — top-level/companion, primitives & String only.

val full get() = "$first $last"

Computed property — value is recomputed on each access via a getter.

var n by Delegates.observable(0) { _, old, new -> }

Delegated property — observe/vetoable/map-backed via `by`.

Scope functions5

x?.let { it.use() }

let — run a block on a non-null value; returns the block's result.

obj.apply { prop = 1 }

apply — configure the receiver via `this`, then return the receiver itself.

x.also { log(it) }

also — perform a side effect with `it`, then return the receiver unchanged.

x.run { } / with(x) { }

run/with — operate on the receiver as `this` and return the block's result.

Receiver/return cheat

let/also → `it`; run/with/apply → `this`. let/run/with return block; apply/also return receiver.

Extensions & generics7

fun String.shout() = uppercase() + "!"

Extension function — add methods to a type you don't own, no subclassing.

val String.lastChar get() = this[length - 1]

Extension property — a computed property added to an external type.

fun Context.toast(msg: String) { }

Android idiom — extend framework types for concise call sites.

fun <T> singletonList(item: T): List<T>

Generic function — a type parameter `<T>` links inputs and outputs.

interface Source<out T> / Sink<in T>

Variance — `out` = producer (covariant), `in` = consumer (contravariant).

fun copy(from: Array<out Any>)

Use-site variance (type projection) at a single call site.

typealias Handler = (Event) -> Unit

typealias — a readable name for a complex/function type (no new type).

Coroutines & suspend7

suspend fun fetch(): User

suspend — a function that can pause without blocking the thread.

scope.launch { }

launch — start a fire-and-forget coroutine; returns a Job (no result).

val r = async { work() }.await()

async/await — run concurrently and get a typed result via Deferred.

withContext(Dispatchers.IO) { }

Switch the dispatcher (thread pool) for a block; suspends until it finishes.

coroutineScope { } / supervisorScope { }

Structured concurrency — children must finish before the scope returns.

delay(1000)

Non-blocking sleep — suspends the coroutine, never blocks the thread (vs Thread.sleep).

flow { emit(x) }.collect { }

Flow — a cold, async stream of values (Kotlin's reactive sequence).