Kotlin Cheatsheet

Syntax

Use this Kotlin reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Variables & types

val name = "Ada"            // immutable reference (prefer this)
var count = 0               // mutable
val score: Int = 95         // explicit type
const val MAX = 100         // compile-time constant (top level / companion)
TypeLiteral / note
Int, Long42, 42L, 1_000_000
Double, Float3.14, 3.14f
Booleantrue, false
Char, String'a', "text"
UInt, ULong42u, 42uL (unsigned)
Any, Unit, Nothingroot type, "no value" return, "never returns"

Conversions are explicit: x.toLong(), s.toInt(), s.toIntOrNull() — no implicit widening.

Strings

val s = "score=$score, next=${score + 1}"   // templates
val raw = """
    no escapes, $templates still work
    line two
""".trimIndent()
FunctionResult
s.length, s[0]length, char access
s.uppercase() / s.lowercase()case (modern names)
s.trim(), s.trimIndent(), s.trimMargin()whitespace / margin strip
s.split(","), s.split(Regex("\\s+"))List<String>
list.joinToString(", ", prefix = "[", postfix = "]")join
s.replace("a", "b"), s.replace(Regex("\\d+"), "#")replace
s.substringBefore(":") / substringAfter(":")cheap parsing
s.startsWith(p), s.contains(p), s.endsWith(p)tests
s.padStart(5, '0'), s.padEnd(5)padding
s.repeat(3), s.reversed(), s.take(2), s.drop(2)misc
s.toIntOrNull(), s.toDoubleOrNull()safe parse (null on failure)

if / when are expressions

val label = if (score >= 90) "A" else "keep going"

val kind = when (code) {                 // with subject
    200 -> "ok"
    in 400..499 -> "client error"
    301, 302 -> "redirect"
    is Int -> "other int"                // type check branch
    else -> "unknown"
}

val desc = when {                        // no subject: first true wins
    x < 0 -> "negative"
    x == 0 -> "zero"
    else -> "positive"
}

when over a sealed type or enum needs no else once every case is listed — the compiler enforces exhaustiveness:

sealed interface Shape
data class Circle(val r: Double) : Shape
data class Rect(val w: Double, val h: Double) : Shape

fun area(s: Shape) = when (s) {          // exhaustive, no else
    is Circle -> 3.141592653589793 * s.r * s.r
    is Rect -> s.w * s.h
}

Kotlin 2.2+ adds guard conditions on branches: is Circle if s.r > 0 -> ....

Loops, ranges & progressions

for (i in 0..<n) { }             // 0 to n-1 (rangeUntil, Kotlin 1.9+)
for (i in 0 until n) { }         // same, older spelling
for (i in 1..10) { }             // inclusive
for (i in 10 downTo 1) { }       // descending
for (i in 0..100 step 5) { }     // stride
for (x in items) { }             // any Iterable
for ((i, x) in items.withIndex()) { }
for ((k, v) in map) { }          // destructuring
while (cond) { }
do { } while (cond)
Range exprMeaning
a..binclusive [a, b]
a..<bend-exclusive [a, b)
a downTo bdescending, inclusive
x in a..bcontainment test
('a'..'z'), (1..9).toList()char ranges, materialize

Labeled breaks: outer@ for (...) { for (...) { break@outer } }.

Exceptions

try is an expression; there are no checked exceptions in Kotlin.

val n = try { s.toInt() } catch (e: NumberFormatException) { 0 }

try {
    risky()
} catch (e: IllegalStateException) {
    log(e)
    throw e                       // rethrow fine
} finally {
    cleanup()
}

val r: Result<Int> = runCatching { s.toInt() }   // functional style
val v = r.getOrDefault(0)
val w = r.getOrElse { e -> -1 }

throw is an expression of type Nothing, so it composes: val x = maybe ?: throw IllegalArgumentException("missing").