Free Kotlin cheat sheet

Kotlin cheat sheet

The Kotlin you look up while coding, on one page: types, null safety, collections, control flow, functions, and data classes.

Variables and typesNull safetyStringsCollectionsControl flowFunctions and lambdasClasses

← All cheat sheets

Kotlin Cheat Sheet

Quick reference from FreeCodingCourses.com

Variables and types

val name = "Ada"
read-only, cannot be reassigned.
var count = 5
mutable.
val price: Double = 9.99
an explicit type is optional.
val ok = true
Boolean.
val big: Long = 10L
Int, Long, Double, Float, Boolean.
val list = listOf(1, 2)
type inferred from the value.
val text: String = "hi"
declare the type after the name.

Null safety

var s: String = "hi"
cannot hold null.
var s: String? = null
the ? makes it nullable.
s?.length
safe call: null if s is null.
s?.length ?: 0
Elvis operator: a default when null.
s!!.length
assert non-null, throws if it is null.
if (s != null) s.length
smart cast after a null check.
val len = s?.length ?: -1
a common null-safe read.

Strings

"Hi $name"
string template with $.
"Total: ${price * qty}"
braces for an expression.
s.uppercase()
uppercase (lowercase for lower).
s.trim()
trim whitespace from both ends.
s.split(",")
split into a list.
list.joinToString(", ")
join a list into a string.
"""..."""
triple-quoted raw multiline string.

Collections

listOf(1, 2, 3)
a read-only list.
mutableListOf(1, 2)
a list you can add to.
mapOf("a" to 1)
a read-only map, key to value.
list.map { it * 2 }
transform each; it is the item.
list.filter { it > 1 }
keep items that pass.
list.first()
first item (last for the last).
list.sumOf { it }
add up a computed field.
map["a"]
read a value by key, may be null.

Control flow

if (x > 0) "pos" else "neg"
if is an expression, it returns.
when (x) { 1 -> "one"; else -> "?" }
when replaces switch.
for (item in list) { }
loop a collection.
for (i in 0..4)
inclusive range, 0 through 4.
for (i in 0 until n)
0 up to but not including n.
while (cond) { }
loop until the condition is false.
list.forEach { println(it) }
run a block per item.

Functions and lambdas

fun add(a: Int, b: Int): Int { }
typed params and return.
fun add(a: Int, b: Int) = a + b
single-expression body.
fun greet(name: String = "friend")
default argument.
greet(name = "Ada")
named argument at the call site.
val sq = { n: Int -> n * n }
a lambda.
fun total(vararg nums: Int)
any number of args.
list.map { it.uppercase() }
trailing lambda, no parentheses.

Classes

class User(val name: String)
primary constructor.
data class User(val name: String, val age: Int)
auto equals, toString, copy.
val u = User("Ada", 36)
no new keyword.
u.copy(age = 37)
clone a data class with one change.
object Config { val env = "prod" }
a singleton.
enum class Status { OK, ERROR }
an enum.
interface Repo { fun find(id: Int): User? }
an interface.

Unlock the full Kotlin cheat sheet

You're seeing 2 of 7 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.

No spam, unsubscribe anytime. See our privacy policy.

Kotlin questions, answered

What is the difference between val and var in Kotlin?

val declares a read-only reference: you assign it once and cannot reassign it, similar to final in Java. var declares a mutable variable you can reassign. Note that val makes the reference constant, not the object, so a val that holds a mutable list can still have items added. Default to val and switch only when needed.

How does Kotlin's null safety actually work?

Types are non-null by default, so String cannot hold null and the compiler rejects it. Add a ? to allow null, as in String?. Then you must handle the null case with a safe call ?., the Elvis operator ?:, or a null check before you can use the value. This moves null bugs from runtime crashes to compile-time errors.

Can Kotlin use Java libraries, and can I mix the two?

Yes. Kotlin runs on the JVM and works with Java both ways inside the same project. You can call any Java library from Kotlin and call Kotlin from Java, and many teams migrate one file at a time. This is a big reason Android adopted Kotlin without forcing teams to rewrite everything at once.

Where to go next