KtKotlin · Lesson 8 of 8

Kotlin Cheatsheet

Null safety, data classes, collections, and coroutines on one page.

Kotlin
// ── Basics ──────────────────────────────
val x = 42                 // read-only (default choice)
var y = 3.14               // mutable
val name: String = "Ada"
println("Hi $name, next: ${x + 1}")

// ── Null safety ─────────────────────────
var s: String? = null      // ? = nullable type
s?.length                  // safe call -> null
s?.length ?: 0             // elvis default
s!!.length                 // crash if null (avoid)
if (s != null) s.length    // smart cast
s?.let { println(it) }     // run only if non-null

// ── Control flow ────────────────────────
val label = if (x > 10) "big" else "small"   // expression
when (x) {
    0        -> "zero"
    in 1..9  -> "small"
    is Int   -> "int"
    else     -> "other"
}
for (i in 1..5) { }        // inclusive
for (i in 0 until 5) { }   // exclusive
for (i in 10 downTo 1 step 2) { }

// ── Functions ───────────────────────────
fun add(a: Int, b: Int = 0): Int = a + b
fun greet(name: String) = "Hi $name"
add(b = 5, a = 1)          // named args
val double = { n: Int -> n * 2 }
Kotlin
// ── Classes ─────────────────────────────
class Student(val name: String, var grade: Int = 0)
data class Point(val x: Int, val y: Int)
// data = equals/hashCode/toString/copy free
val p2 = p1.copy(y = 5)
val (a, b) = p2                     // destructuring

sealed class Result
data class Ok(val data: String) : Result()
data class Err(val msg: String) : Result()
// when(result) is exhaustive — no else needed

object Config { val version = "1.0" }   // singleton
enum class Color { RED, GREEN }

// ── Collections ─────────────────────────
val nums = listOf(3, 1, 4)              // read-only
val mut = mutableListOf(1, 2)
val ages = mapOf("Ada" to 17)
ages["Ada"]

nums.filter { it > 1 }
    .map { it * 2 }
    .sorted()
nums.sumOf { it }; nums.maxByOrNull { it }
nums.any { it > 3 }; nums.groupBy { it % 2 }
nums.forEach { println(it) }
nums.firstOrNull { it > 10 } ?: -1

// ── Coroutines ──────────────────────────
suspend fun fetch(): String { delay(1000); return "data" }

runBlocking {
    val a = async { fetch() }       // concurrent
    val b = async { fetch() }
    println(a.await() + b.await())  // ~1s total
    launch { sideEffect() }         // fire and forget
    withContext(Dispatchers.IO) { readFile() }
}

// ── Scope functions ─────────────────────
obj.let { it.thing() }     // transform, null-guard
obj.apply { prop = 1 }     // configure, returns obj
obj.also { log(it) }       // side effect, returns obj
with(obj) { method() }     // grouping