Skip to content

Kotlin Cheat Sheet

Kotlin is a modern, concise, and strongly typed programming language targeting the JVM and multiple platforms. This Kotlin cheatsheet provides an example-driven reference covering core syntax, null safety, collections, object-oriented features, and coroutine-based concurrency.


Minimal Program

fun main() {
    println("Hello, Kotlin")
}

Variables

var a = 10
val b = 20
var c: Int = 30
val d: String = "text"

Basic Types

Int
Long
Double
Float
Boolean
Char
String
val x: Int = 10
val y: Double = 3.14

Null Safety

var value: Int? = null
val length = value?.toString()?.length
val result = value ?: 0
value!!

Strings

val s = "Kotlin"
s.uppercase()
s.contains("lin")
val name = "World"
println("Hello $name")
println("2 + 2 = ${2 + 2}")

Operators

a + b
a - b
a * b
a / b
a % b
a == b
a != b
a > b
a < b
a && b
a || b
!a

Control Flow

if Expression

val max = if (a > b) a else b

when

val label = when (a) {
    1 -> "one"
    2 -> "two"
    else -> "other"
}

Loops

for (i in 0 until 5) {
    println(i)
}
while (a > 0) {
    a--
}
for (item in list) {
    println(item)
}

Functions

fun add(a: Int, b: Int): Int {
    return a + b
}
val r = add(2, 3)

Single-Expression Functions

fun square(x: Int): Int = x * x

Default & Named Parameters

fun connect(host: String, port: Int = 80) {
}
connect("localhost")
connect(host = "localhost", port = 8080)

Vararg Parameters

fun sum(vararg nums: Int): Int {
    return nums.sum()
}

Collections

List

val list = listOf(1, 2, 3)
val mutable = mutableListOf(1, 2, 3)
mutable.add(4)

Set

val set = setOf(1, 2, 3)

Map

val map = mapOf("a" to 1, "b" to 2)

Iteration

list.forEach { println(it) }
for ((k, v) in map) {
    println("$k=$v")
}

Classes

class Counter {
    var value = 0
    fun increment() {
        value++
    }
}
val c = Counter()
c.increment()

Constructors

class Point(val x: Int, val y: Int)
val p = Point(10, 20)

Data Classes

data class User(val name: String, val age: Int)
val u = User("A", 20)

Sealed Classes

sealed class Result
class Success(val value: Int) : Result()
class Error(val msg: String) : Result()
fun handle(r: Result) = when (r) {
    is Success -> r.value
    is Error -> 0
}

Enums

enum class Status {
    OK, ERROR, LOADING
}

Inheritance

open class Animal {
    open fun speak() {}
}

class Dog : Animal() {
    override fun speak() {}
}

Interfaces

interface Logger {
    fun log(msg: String)
}
class ConsoleLogger : Logger {
    override fun log(msg: String) {
        println(msg)
    }
}

Object Declarations

object Config {
    val version = "1.0"
}

Companion Objects

class Factory {
    companion object {
        fun create(): Factory = Factory()
    }
}

Generics

class Box<T>(val value: T)
val box = Box(10)

Lambdas

val inc: (Int) -> Int = { it + 1 }

Higher-Order Functions

fun apply(x: Int, f: (Int) -> Int): Int {
    return f(x)
}

Coroutines

import kotlinx.coroutines.*

runBlocking {
    launch {
        delay(100)
        println("done")
    }
}

Async / Await

runBlocking {
    val deferred = async {
        42
    }
    println(deferred.await())
}

Flows

import kotlinx.coroutines.flow.*

flowOf(1, 2, 3)
    .map { it * 2 }
    .collect { println(it) }

Exception Handling

try {
    val x = "10".toInt()
} catch (e: NumberFormatException) {
} finally {
}

File I/O (JVM)

import java.io.File

File("file.txt").writeText("text")
val text = File("file.txt").readText()

Type Casting

val obj: Any = "text"

if (obj is String) {
    println(obj.length)
}