Kotlin Cheatsheet

Quick reference for Kotlin syntax. Print-friendly.

Variables

val name = "Kotlin"   // read-only
var count = 0         // mutable
count = 1             // reassign var

Data Types

val i: Int = 42
val d: Double = 3.14
val b: Boolean = true
val c: Char = 'A'
val s: String = "hello"

String Templates

val name = "World"
println("Hello, $name!")         // Hello, World!
println("${name.length} chars")  // 5 chars

If / Else

val x = if (score >= 60) "Pass" else "Fail"
if (n > 0) {
    println("Positive")
} else if (n < 0) {
    println("Negative")
} else {
    println("Zero")
}

When

val result = when (day) {
    1 -> "Monday"
    6, 7 -> "Weekend"
    in 2..5 -> "Weekday"
    else -> "Unknown"
}

For Loop

for (i in 1..5) println(i)
for (i in 5 downTo 1 step 2) println(i)
for (item in list) println(item)

While Loop

var i = 0
while (i < 5) { println(i); i++ }
do { println(i); i++ } while (i < 5)

Functions

fun greet(name: String = "World"): String {
    return "Hello, $name"
}
fun double(x: Int) = x * 2  // single expression

Lists

val list = listOf(1, 2, 3)       // immutable
val mList = mutableListOf(1, 2)  // mutable
mList.add(3)
println(list[0])  // 1

Maps

val map = mapOf("a" to 1, "b" to 2)
val mMap = mutableMapOf("x" to 10)
mMap["y"] = 20
println(map["a"])  // 1

Null Safety

var name: String? = null  // nullable
println(name?.length)    // null (safe call)
println(name?.length ?: 0) // 0 (Elvis)
val len = name!!.length   // throws if null

Classes

class Person(val name: String, var age: Int)
data class User(val id: Int, val name: String)
val p = Person("Juned", 25)
val u = User(1, "Kotlin")

Inheritance

open class Animal { open fun sound() = "..." }
class Dog : Animal() {
    override fun sound() = "Bark"
}

Lambdas

val double = { x: Int -> x * 2 }
val nums = listOf(1,2,3)
val doubled = nums.map { it * 2 }
val evens = nums.filter { it % 2 == 0 }

Scope Functions

// apply: configure object, returns it
val p = Person().apply { name = "Juned" }
// let: transform, returns result
val len = name?.let { it.length } ?: 0
// also: side effect, returns original
val list = mutableListOf(1).also { it.add(2) }

Coroutines

// Add: kotlinx-coroutines-core
import kotlinx.coroutines.*
fun main() = runBlocking {
    launch { delay(1000); println("done") }
    val r = async { 10 + 20 }.await()
}

Flow

// Add: kotlinx-coroutines-core
import kotlinx.coroutines.flow.*
flowOf(1,2,3).map{it*2}.collect{println(it)}
// StateFlow:
val state = MutableStateFlow(0)
state.value = 1