Kotlin Basics Cheatsheet

Quick reference for Kotlin basics: variables, types, functions, classes, control flow, collections, and standard library usage.

ItemDescriptionExampleCategory
valImmutable variableval x = 10Variables
varMutable variablevar y = 5Variables
Int, Double, String, BooleanBasic typesval age: Int = 20 val name: String = "Alice"Types
AnySuper type of all typesval obj: Any = "Hello"Types
UnitReturn type like voidfun printHello(): Unit { println("Hello") }Types
Null safetyNullable typeval s: String? = nullTypes
if / elseConditional statementsif(x > 0) println("Positive") else println("Non-positive")ControlFlow
whenSwitch equivalentwhen(x) { 1 -> println("One") else -> println("Other") }ControlFlow
for loopIterate over ranges/collectionsfor(i in 1..5) println(i)ControlFlow
while / do-whileLoopingwhile(x>0){ x-- }ControlFlow
funDeclare functionfun sum(a: Int, b: Int): Int = a + bFunctions
Default & Named argsFunction with defaultsfun greet(name: String="User") { println("Hello $name") }Functions
Extension functionAdd function to existing typefun String.exclaim() = this + "!"Functions
classDefine classclass Person(val name: String, var age: Int)Classes
data classClass with auto-generated methodsdata class Point(val x:Int, val y:Int)Classes
objectSingleton objectobject Logger { fun log(msg:String) { println(msg) } }Classes
ListImmutable listval list = listOf(1,2,3)Collections
MutableListMutable listval mlist = mutableListOf(1,2,3)Collections
Set / MapImmutable set/mapval s = setOf(1,2); val m = mapOf("a" to 1)Collections
MutableSet / MutableMapMutable set/mapval ms = mutableSetOf(1,2); val mm = mutableMapOf("a" to 1)Collections
LambdaAnonymous functionval square = { x:Int -> x*x }Others
let / apply / run / alsoScope functionsval len = s?.let { it.length }Others
Safe call / Elvis operatorHandle nullable valuesval len = s?.length ?: 0Others