Kotlin Basics Cheatsheet
Quick reference for Kotlin basics: variables, types, functions, classes, control flow, collections, and standard library usage.
| Item | Description | Example | Category |
|---|---|---|---|
| val | Immutable variable | val x = 10 | Variables |
| var | Mutable variable | var y = 5 | Variables |
| Int, Double, String, Boolean | Basic types | val age: Int = 20 val name: String = "Alice" | Types |
| Any | Super type of all types | val obj: Any = "Hello" | Types |
| Unit | Return type like void | fun printHello(): Unit { println("Hello") } | Types |
| Null safety | Nullable type | val s: String? = null | Types |
| if / else | Conditional statements | if(x > 0) println("Positive") else println("Non-positive") | ControlFlow |
| when | Switch equivalent | when(x) { 1 -> println("One") else -> println("Other") } | ControlFlow |
| for loop | Iterate over ranges/collections | for(i in 1..5) println(i) | ControlFlow |
| while / do-while | Looping | while(x>0){ x-- } | ControlFlow |
| fun | Declare function | fun sum(a: Int, b: Int): Int = a + b | Functions |
| Default & Named args | Function with defaults | fun greet(name: String="User") { println("Hello $name") } | Functions |
| Extension function | Add function to existing type | fun String.exclaim() = this + "!" | Functions |
| class | Define class | class Person(val name: String, var age: Int) | Classes |
| data class | Class with auto-generated methods | data class Point(val x:Int, val y:Int) | Classes |
| object | Singleton object | object Logger { fun log(msg:String) { println(msg) } } | Classes |
| List | Immutable list | val list = listOf(1,2,3) | Collections |
| MutableList | Mutable list | val mlist = mutableListOf(1,2,3) | Collections |
| Set / Map | Immutable set/map | val s = setOf(1,2); val m = mapOf("a" to 1) | Collections |
| MutableSet / MutableMap | Mutable set/map | val ms = mutableSetOf(1,2); val mm = mutableMapOf("a" to 1) | Collections |
| Lambda | Anonymous function | val square = { x:Int -> x*x } | Others |
| let / apply / run / also | Scope functions | val len = s?.let { it.length } | Others |
| Safe call / Elvis operator | Handle nullable values | val len = s?.length ?: 0 | Others |