Lesson 129 of 134 ยท Practice
Kotlin Cheat Sheet
A one-page Kotlin cheat sheet with runnable examples: variables, null safety, when, functions, lambdas, classes, collections, strings, errors and coroutines, with links to full lessons.
This page is a quick reference for the Kotlin you use every day. It is not a tutorial: each block is short, runs as it stands, and links to the lesson that explains the topic properly. Skim it when you forget the name of a function, or read it from top to bottom as a revision before an interview.
Every example is a complete program. Press Run to see the output, then change a line and run again. Kotlin 2.x syntax is used throughout.
Basics: variables, types, strings, ranges
| You want | Write |
|---|---|
| Read-only variable | val x = 5 |
| Mutable variable | var n = 0 |
| Compile-time constant | const val MAX = 10 (top level or in an object) |
| Explicit type | val s: String = "hi" |
| Integer division / remainder | 7 / 2 is 3, 7 % 2 is 1 |
| Convert numbers | x.toLong(), s.toInt(), s.toIntOrNull() |
| String template | "Hello, $name! ${a + b}" |
| Multi-line string | """text""" with trimIndent() |
See Variables, Basic Types, Numbers and Strings.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.
Null safety and control flow
A type with ? can hold null; the compiler then forces you to handle it. if, when and try are expressions that produce values. See Null Safety, if as an Expression and when Expressions.
| Operator | Meaning |
|---|---|
a?.b |
b of a, or null if a is null |
a ?: default |
a if not null, otherwise default |
a!! |
a, or throws NullPointerException (avoid) |
a as? T |
cast, or null if it fails |
a?.let { ... } |
run the block only when a is not null |
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.
is Int if x > 100 is a guard condition in when. It compiles on this site's Kotlin 2.4 runner without any flag; if your project uses an older compiler, check the lesson on when Expressions first, and fall back to a plain is Int -> if (x > 100) ... else ... branch.
Functions, lambdas and extensions
| You want | Write |
|---|---|
| Function | fun add(a: Int, b: Int): Int = a + b |
| Default and named arguments | fun f(x: Int = 1), call f(x = 2) |
| Varargs | fun sum(vararg n: Int), call sum(*array) |
| Lambda | { x: Int -> x * 2 }, or { it * 2 } |
| Function type | (Int) -> Int |
| Function reference | ::isEven, String::length |
| Extension function | fun String.shout() = uppercase() + "!" |
Scope functions: let (value it, returns the lambda result), also (it, returns the object), apply (this, returns the object), run (this, returns the result), with(obj) { }. See Functions, Lambdas, Extension Functions and Scope Functions.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.
Classes and objects
| You want | Write |
|---|---|
| Class with properties | class P(val name: String, var age: Int) |
| Data class | data class Point(val x: Int, val y: Int) |
| Singleton | object Config { val debug = true } |
| Companion (static-like) | companion object { fun create() = ... } |
| Enum | enum class Color { RED, GREEN }, list with Color.entries |
| Sealed hierarchy | sealed interface Shape |
| Interface with default | interface A { fun f() = 1 } |
| Inheritance | open class Base, class Child : Base() |
| Delegation | class X(b: B) : B by b, val v by lazy { ... } |
Classes are final unless marked open. See Classes, Data Classes, Sealed Classes and Interfaces, Enum Classes and Delegation.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.
Collections
Kotlin has read-only views (List, Set, Map) and mutable types (MutableList, ...). Create them with listOf, mutableListOf, setOf, mapOf, buildList. Chains of map, filter and friends do the work of loops. Use asSequence() for long pipelines. See Collections Overview, Collection Transformations, Maps and Sequences.
| Operation | Function |
|---|---|
| Transform each item | map, mapIndexed, flatMap |
| Keep items | filter, filterNot, take, drop, distinct |
| Find | first, firstOrNull, find, any, all, none, count |
| Combine | sum, fold, reduce, joinToString |
| Group and split | groupBy, partition, chunked, windowed, associateBy |
| Order | sorted, sortedBy, sortedByDescending, reversed |
| Pair up | zip, withIndex, to |
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.
Errors and results
Kotlin has no checked exceptions. try is an expression; require, check and error state conditions; runCatching wraps a computation in a Result; use closes resources. See Exceptions, Preconditions and The Result Type.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.
Coroutines
Add suspend to a function that can pause. Start coroutines with launch (no result) or async (a result you await) inside a scope; runBlocking bridges ordinary code into that world, and flow produces a stream of values. coroutineScope waits for its children. See Coroutines, Suspend Functions, Coroutine Builders and Flows.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.
Check your understanding
Quick check ยท 4 questions
of 4 answered You scored / 4 ยท perfect!
-
1. Which declaration creates a read-only variable?
valdeclares a variable that cannot be reassigned.varis mutable, andletand bareconstare not Kotlin declarations. -
2. What does
name?.length ?: 0give whennameisnull??.yieldsnullfor a null receiver, and the elvis operator?:replaces thatnullwith0. -
3. Which function splits a list into two lists by a condition?
partitionreturns aPairof the matching and the non-matching items.groupBymakes a map with any number of groups, andchunkedsplits by size. -
4. Which keyword starts a coroutine that returns a result you can await?
asyncreturns aDeferredwhoseawait()gives the result.launchreturns aJobwith no result, anddelayonly suspends.
Summary
valfor read-only,varfor mutable, types are inferred, and?marks nullable types.- Use
?.,?:andletfor null handling; avoid!!. if,whenandtryproduce values; awhenover a sealed type needs noelse.- Functions can have default and named arguments; lambdas, references and extensions are everyday tools.
- Data classes, sealed types, enums and objects cover most modelling needs.
- Learn the collection operations (
map,filter,groupBy,fold,sortedBy) and use sequences for long chains. - Use
requireandcheckfor preconditions,runCatchingfor results, andusefor resources. suspend,launch,asyncandfloware the core of coroutines.
Next: Common Kotlin Mistakes
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of Kotlin lessons completed