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.