KtKotlin

Kotlin cheatsheet – syntax overview

81 key commands and patterns for quick reference.

Basics Types & Strings Control flow Functions & Lambdas Null safety Classes & Objects Collections Collection operations Errors & Files Coroutines & Flow

Basics

println("Text") print("no line break")Output
val x = 5 var y = 6val = immutable, var = mutable
val s: String = "Text"Specify the type explicitly
"Hello $name, ${a + b}"String template
val z = readln()Read input as a string
// Comment /* Block */ /** KDoc */Comments
fun main() { }Entry point

Types & Strings

Int Long Double Float Boolean Char String Any UnitImportant types
"42".toInt() "x".toIntOrNull() 5.toDouble()Conversion (always explicit)
s.length s.uppercase() s.lowercase() s.trim()Common string properties
s.split(",") list.joinToString(", ")Split and join
s.substring(1, 4) s.take(3) s.drop(2)Substrings
s.contains("a") "a" in s s.startsWith("x")Check containment and prefix
"""mehrzeilig""".trimIndent()Raw string
s.replace("a", "b") s.reversed() s.repeat(3)Replace, reverse, repeat

Control flow

if (x > 0) "pos" else "not pos"if as an expression
when (x) { 1 -> "a"; in 2..5 -> "b"; else -> "c" }when with values and ranges
when { x < 0 -> "neg"; else -> "pos" }when without an argument
for (i in 1..5) for (i in 0 until 5)Loop over a range (inclusive / exclusive end)
for (i in 10 downTo 1 step 3)Backwards with a step size
for ((i, x) in liste.withIndex())Index and value
while (bed) { } do { } while (bed)Loops with a condition
break continue break@label repeat(3) { }Break, continue, label, repeat

Functions & Lambdas

fun f(a: Int, b: Int = 2): Int { return a + b }Function with a default value
fun f(a: Int) = a * 2Expression body
f(b = 1, a = 2)Named arguments
fun f(vararg x: Int) f(*array)vararg and spread operator
val g = { x: Int -> x * 2 }Lambda
fun h(op: (Int) -> Int) = op(1) h { it + 1 }Higher-order function with trailing lambda
fun String.doppelt() = this + thisExtension function
inline fun <reified T> f() { }inline with a reified type

Null safety

var s: String? = nullNullable type
s?.lengthSafe call: null if s is null
s ?: "standard"Elvis: fallback value for null
s!!.lengthThrows an NPE on null (avoid)
s?.let { println(it) }Block only for non-null
x as? StringSafe cast (null on failure)
val n = s ?: returnExit early on null
list.filterNotNull() requireNotNull(x)Remove null values / enforce non-null

Classes & Objects

class A(val x: Int, var y: Int = 0)Class with a primary constructor and properties
open class A class B : A()Inheritance (open required)
interface I { fun f() = 1 }Interface with a default method
data class P(val x: Int, val y: Int)Data class (equals, copy, toString)
p.copy(y = 5) val (x, y) = pCopying and destructuring
enum class Farbe { ROT, GRUEN } Farbe.entriesEnum and all its values
object Logger companion object { }Singleton and companion
sealed interface S class A : SClosed hierarchy
class A { val x by lazy { 42 } }Delegated property lazy

Collections

listOf(1, 2) mutableListOf(1, 2)List: read-only / mutable
setOf(1, 2) mapOf("a" to 1)Set and map
l[0] l.first() l.last() l.sizeAccess and size
l.add(x) l.remove(x) l += xModify a mutable list
m["a"] m.getValue("a") m["b"] = 2Read and write a map
for ((k, v) in m) { }Iterate over a map
x in liste l.isEmpty() l.contains(x)Queries
l.sorted() l.sortedBy { it.x } l.reversed()Sort, reverse (new list)

Collection operations

l.filter { it > 1 } l.map { it * 2 }Filter and transform
l.sum() l.sumOf { it.x } l.average()Sum and average
l.max() l.min() l.maxByOrNull { it.x }Maximum and minimum
l.groupBy { it.x } l.associateBy { it.id }Group / index by key
l.any { } l.all { } l.none { } l.count { }Check and count
l.fold(0) { acc, x -> acc + x }Combine (reduce)
l.zip(m) l.flatMap { } l.distinct()Zip, flatten, remove duplicates
l.take(3) l.drop(2) l.chunked(2) l.windowed(2)Sub-parts
l.asSequence().filter { }.take(3).toList()Lazy sequence

Errors & Files

try { } catch (e: Exception) { } finally { }Error handling (also as an expression)
throw IllegalArgumentException("Text")Throw an error
require(x > 0) { "Text" } check(ok)Check arguments / state
runCatching { f() }.getOrNull()Result instead of exception
File("a.txt").readText() .readLines()Read a file
File("a.txt").writeText("x") .appendText("y")Write a file
File("a.txt").useLines { it.count() }Read line by line, close automatically
file.bufferedReader().use { it.readLine() }Close a resource with use

Coroutines & Flow

suspend fun f() { delay(100) }Suspend function
runBlocking { }Start the coroutine world from main
launch { } val d = async { 1 }; d.await()Start without / with a result
coroutineScope { }Structured concurrency: waits for children
withContext(Dispatchers.IO) { }Switch context (thread pool)
job.cancel() withTimeout(1000) { }Cancel, timeout
flow { emit(1) } flow.collect { }Create and collect a flow
flow.map { }.filter { }.first()Flow operators