Skip to content
AgileLogics

Kotlin Cheat Sheet

Learn Kotlin from the basics →

Variables & Types

val name = "Ada"
Read-only variable (prefer by default)
var score = 0
Mutable variable
val price: Double = 9.99
Explicit type
const val MAX_USERS = 100
Compile-time constant (top level or in an object)
"42".toInt() / "42".toIntOrNull()
Convert — throwing vs null-returning

Strings

"Hello, $name! You are ${age + 1}"
String templates
s.length / s.isEmpty() / s.isBlank()
Length and emptiness
s.uppercase() / s.lowercase()
Change case
s.trim() / s.split(",")
Trim / split
s.startsWith("He") / "ll" in s
Prefix / substring check
val text = """ ... """.trimIndent()
Raw multi-line string (no escapes processed)

Null Safety

var email: String? = null
Nullable type
email?.length
Safe call — null if email is null
val n = email?.length ?: 0
Elvis operator — default value
email?.let { send(it) }
Run only if not null
email!!.length
Non-null assertion (throws if null)

Control Flow

val max = if (a > b) a else b
if is an expression
when (x) { 1, 2 -> "low"; in 3..9 -> "mid"; else -> "high" }
when expression
for (i in 1..5) { }
Inclusive range
for (i in 0..<n) { } / for (i in 10 downTo 0 step 2) { }
Exclusive range / reverse with step
for ((i, v) in list.withIndex()) { }
Index and value

Collections

val nums = listOf(1, 2, 3)
Read-only list
val items = mutableListOf<String>()
Mutable list
val ages = mapOf("ada" to 36)
Map (key to value)
ages.getOrDefault("bob", 0)
Lookup with a default
nums.map { it * 2 }.filter { it > 2 }
Transform and filter
people.groupBy { it.city } / sortedBy { it.age }
Group / sort by a property

Functions & Lambdas

fun add(a: Int, b: Int = 0): Int = a + b
Default argument, expression body
greet(name = "Ada", loud = true)
Named arguments
val double = { n: Int -> n * 2 }
Lambda
fun String.shout() = uppercase() + "!"
Extension function
user.apply { age = 37 }.also { log(it) }
Scope functions

Classes

class User(val name: String, var age: Int)
Class with a primary constructor
data class Point(val x: Int, val y: Int)
Data class: equals, toString, copy
open class Animal / class Dog : Animal()
Inheritance (classes are final by default)
object Config { val debug = true }
Singleton object
sealed interface Result { data class Ok(val v: Int) : Result }
Sealed hierarchy for exhaustive when
enum class Color { RED, GREEN }
Enum class

Coroutines

suspend fun load(): User
Suspending function
runBlocking { launch { work() } }
Start coroutines (in main or tests)
val a = async { fetchA() }; a.await()
Concurrent result
withContext(Dispatchers.IO) { readFile() }
Switch to an I/O thread pool
flow { emit(1) }.collect { println(it) }
Cold asynchronous stream

Tooling

kotlinc app.kt -include-runtime -d app.jar
Compile to a runnable JAR
java -jar app.jar
Run it
./gradlew build / ./gradlew run
Build / run a Gradle project
./gradlew test
Run tests