Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Kotlin Cheat Sheet

Basics

val x = 5; var y = 10; const val MAX = 100
println("x = $x, sum = ${x + y}")
val n = readln().toInt(); val parts = readln().split(" ").map { it.toInt() }
val s: String? = null; s?.length ?: 0

Control flow

val max = if (a > b) a else b
when (x) { 1, 2 -> "low"; in 3..9 -> "mid"; else -> "high" }
for (i in 0 until n) { } for (i in n downTo 1 step 2) { }
for ((i, v) in list.withIndex()) { }
repeat(3) { }

Functions

fun add(a: Int, b: Int = 0) = a + b
fun String.shout() = uppercase() + "!"
val sq = { x: Int -> x * x }
list.forEach { println(it) }

Collections

val l = listOf(1, 2); val ml = mutableListOf(1); ml.add(2)
val m = mapOf("a" to 1); val mm = mutableMapOf<String, Int>(); mm["b"] = 2
list.filter { it > 0 }.map { it * 2 }.sum()
list.sortedBy { it.age }; list.groupBy { it.dept }; list.associateBy { it.id }
list.firstOrNull { it > 5 }; list.any { }; list.all { }; list.count { }

Classes

class User(val name: String, var age: Int)
data class Point(val x: Int, val y: Int)
open class A { open fun f() {} }; class B : A() { override fun f() {} }
object Singleton { }
sealed class State { object Loading : State() }

Coroutines

suspend fun load(): String { delay(100); return "x" }
runBlocking { val a = async { load() }; println(a.await()) }
viewModelScope.launch { }

Full Kotlin documentation