Skip to main content
Quick Reference

Kotlin Cheatsheet

Kotlin on one page — null safety, collections, data classes, when, extensions, coroutines, and the traps around !!, val, and equals.

10 sections 10 tables 14 code snippets

Run a file

A script

kotlin hello.main.kts

A value and a variable

val title = "Dune"
var pages = 412
pages += 1
println(title)

The names

NameMeaning
valThe name cannot be reassigned. The object it points at can still change
varThe name can be reassigned. The type stays the one inferred first
Inference412 is an Int. 412.0 is a Double. 412L is a Long
printlnWrites a line. A semicolon is optional
nullOnly a type ending in ? can hold it
kotlinRuns a .main.kts script. kotlinc compiles. Android Studio is the IDE, not the language

This page is the Kotlin language. The samples run as a script or in IntelliJ.

Null safety

Check, then use

val published: Int? = null
if (published != null) {
  println(published + 1)
}

A stand-in

val shown = published ?: 2026
println(shown)

Null rules

FormResult
Int?Either an Int or null
Smart castAfter != null on a local val, the name is an Int inside the block
?:Uses the right-hand value when the left one is null
?.Skips the call when the receiver is null. The whole expression stays nullable
!!Throws NullPointerException when the value is null
A var propertyIs not smart-cast. Another call could change it between the check and the use

Collections

A read-only list

val books = listOf("Dune", "Neuromancer")
println(books[0])

A map

val prices = mapOf("Dune" to 18.5)
val price = prices["Dune"] ?: 0.0
println(price)

Collection rules

TypeDetail
listOfA read-only List. books[0] throws when the index is missing
mutableListOfHas add. A val can still call add, because the name did not change
mapOfThe subscript returns null when the key is absent
setOfUnique values. Order is not part of the contract
1..3Includes 3. 0 until books.size stops before the size
listOf equalityCompares the items. arrayOf compares the references, so two equal-looking arrays are not ==

Functions

A default argument

fun total(price: Double, count: Int = 1): Double {
  return price * count
}
println(total(price = 18.5, count = 2))

Call rules

PieceEffect
price:A named argument. Named arguments can appear in any order
count: Int = 1A default. Callers may omit it
: DoubleThe return type. A function with no useful result returns Unit
Single expressionfun total(price: Double) = price when the body is one expression
Trailing lambdabooks.forEach { println(it) }. it is the argument when the lambda has one
throwLeaves the function. return title ?: throw IllegalStateException() is a common form

Data classes

Constructor properties

data class Book(val title: String, var pages: Int)
val book = Book("Dune", 412)
val copy = book.copy(pages = 500)

Which members you get

KindBehavior
data classGenerates equals, hashCode, toString, copy, and componentN from the constructor properties
Body propertyA var declared in the class body is left out of equals and copy
==Calls equals. Two data objects with the same constructor values compare equal
===The same instance. For Int, this matches ==
A plain classFinal unless you mark it open. equals is identity until you override it
objectA single instance. A companion object holds factory functions on the class

When

A value from the pages

val label = when (pages) {
  0 -> "empty"
  in 1..300 -> "short"
  else -> "long"
}
println(label)

Branch rules

FormMeaning
when as a valueMust cover every possibility, or end with else
in 1..300Matches the range, including both ends
is BookChecks the type and smart-casts the subject in that branch
Sealed typeThe compiler knows every subtype, so else can be omitted once they are all listed
for (book in books)Walks the items
if as a valueval label = if (pages > 300) "long" else "short"

Require and throw

Reject a bad value

fun load(title: String?): String {
  require(!title.isNullOrBlank())
  return title
}

Failure rules

CallThrows
requireIllegalArgumentException when the condition is false. A caller sent a bad argument
checkIllegalStateException when this object is in the wrong state
errorAlways throws IllegalStateException with the message you pass
?: throwTurns a null into the exception you choose
lateinitA var filled in later. Reading it first throws. It cannot be nullable or a primitive
by lazyComputes the val on first read. The type stays non-null

Extension functions

A function on String

fun String.wordCount(): Int {
  return split(" ").size
}
println("Dune Messiah".wordCount())

How dispatch works

FactDetail
Resolved staticallyThe compiler picks the extension from the declared type, not the runtime type
A member winsIf the class already has that function, the member is called and the extension is ignored
Nullable receiverfun String?.orEmptyTitle() can be called on null
open and overrideRequired to inherit and replace a member. An extension cannot do that job
ScopeAn extension is visible where it is imported. It is not added inside the class
applybook.apply { pages = 500 } returns the same book. let returns the lambda result

Coroutines

A suspending function

suspend fun fetchTitle(): String {
  kotlinx.coroutines.delay(10)
  return "Dune"
}

Concurrency rules

PieceMeaning
suspendThe function may pause. Call it from another suspend function or a coroutine builder
Librarydelay, launch, and async live in kotlinx.coroutines, not the standard library
launchStarts work and returns a Job. Use it when you do not need a result
asyncReturns a Deferred. await gets the value
runBlockingBlocks a thread until the coroutine finishes. Fine for main and tests
delaySuspends and can be cancelled. Thread.sleep blocks the thread and ignores cancellation

Interview traps

Traps worth memorising

TrapWhat happensPrefer
title!! when title is nullThrows NullPointerException?:, ?., or an if check
val books = mutableListOf("Dune")The name is fixed. books.add still workslistOf when nothing should be added
books[9] on a short listThrows. A list lookup is not nullableCheck size, or getOrNull
prices["missing"]Returns null?: or getOrElse
arrayOf(1) == arrayOf(1)False. Arrays compare referenceslistOf, or contentEquals
Two data objects that differ only in a body var== is true. equals ignores that propertyPut every field that matters in the constructor
A plain class and ==Identity, until you override equalsA data class when the values should match
Smart-casting a var propertyDoes not compile. The property might changeA local val copy
A Java String used as StringA platform type. It can still be null at runtimeAnnotate the Java method, or check for null
"Book $title"Inserts the value of title. A dollar before a name is a templateEscape the dollar when you want the character
GlobalScope.launchLives for the whole process and is easy to leakA CoroutineScope that cancels with the screen
Thread.sleep inside a coroutineBlocks a thread. Cancellation waitsdelay

This throws on null

val title: String? = null
println(title!!)

This throws on the index

val books = listOf("Dune")
println(books[3])

How to use this page: run kotlin hello.main.kts, keep title as a val, and read published only after a null check. Then make Book a data class, and call a suspend function from a coroutine.