Kotlin
Updated: May 22, 2026Categories: Languages, Mobile
Printed from:
Kotlin Cheatsheet
Language Overview
Kotlin is a modern, statically-typed programming language developed by JetBrains. Key features include:
- 100% interoperability with Java
- Null safety
- Concise and expressive syntax
- First-class support for functional programming
- Runs on the Java Virtual Machine (JVM)
- Supports multiplatform development (Kotlin Multiplatform is stable)
Basic Syntax
Hello World
Kotlin
1234fun main() {
println("Hello, Kotlin!")
}
Comments
Kotlin
123456// Single-line comment
/*
Multi-line
comment
*/
/**
* KDoc documentation comment
* Used for generating API documentation with Dokka
*/
Data Types
Primitive Types
Kotlin
123456789101112131415161718192021222324252627// Integers
val byte: Byte = 127 // 8-bit signed integer
val short: Short = 32767 // 16-bit signed integer
val int: Int = 2_147_483_647 // 32-bit signed integer
val long: Long = 9_223_372_036_854_775_807L // 64-bit signed integer
// Unsigned Integers (stable since Kotlin 1.5)
val uByte: UByte = 255u
val uInt: UInt = 4_294_967_295u
val uLong: ULong = 18_446_744_073_709_551_615uL
// Floating Point
val float: Float = 3.14f // 32-bit floating point
val double: Double = 3.14159 // 64-bit floating point
// Boolean
val bool: Boolean = true
// Character
val char: Char = 'A'
// String
val str: String = "Kotlin is awesome!"
// Multiline strings with trimIndent()
val multiline = """
|Line 1
|Line 2
""".trimMargin()
Nullable Types
Kotlin
12345678910111213141516// Nullable vs Non-Nullable Types
var nonNullableInt: Int = 42 // Cannot be null
var nullableString: String? = null // Can be null
// Safe call operator
val length = nullableString?.length // Returns null if nullableString is null
// Elvis operator (provide default value)
val safeLength = nullableString?.length ?: 0
// Not-null assertion (use sparingly)
val forcedLength = nullableString!!.length
// Safe casts
val asInt: Int? = "123" as? Int
Collection Types
Kotlin
1234567891011121314151617181920// Immutable Lists
val immutableList: List<String> = listOf("Apple", "Banana", "Cherry")
// Mutable Lists
val mutableList: MutableList<String> = mutableListOf("Apple", "Banana")
mutableList.add("Cherry")
// Sets
val immutableSet: Set<Int> = setOf(1, 2, 3)
val mutableSet: MutableSet<Int> = mutableSetOf(1, 2, 3)
// Maps
val immutableMap: Map<String, Int> = mapOf("one" to 1, "two" to 2)
val mutableMap: MutableMap<String, Int> = mutableMapOf("one" to 1)
mutableMap["two"] = 2
// Arrays
val intArray: IntArray = intArrayOf(1, 2, 3)
val stringArray: Array<String> = arrayOf("a", "b", "c")
Variables and Constants
Kotlin
12345678910111213141516171819202122// Immutable variable (read-only, like final in Java)
val pi: Double = 3.14159
// Compile-time constant (must be top-level or in object/companion object)
const val MAX_USERS = 100
// Mutable variable
var counter: Int = 0
// Type inference
val name = "Kotlin" // Type is inferred as String
var age = 30 // Type is inferred as Int
// Late initialization (for non-null var properties)
lateinit var lateInitVar: String
// Lazy initialization (val only)
val expensiveValue: String by lazy {
// Computed only on first access
"Expensive Computation"
}
Operators
Arithmetic Operators
Kotlin
123456val sum = 5 + 3 // Addition
val diff = 5 - 3 // Subtraction
val prod = 5 * 3 // Multiplication
val div = 6 / 3 // Division
val mod = 5 % 3 // Modulus
Comparison Operators
Kotlin
12345678910val a = 5
val b = 3
println(a == b) // Structural equality (calls equals)
println(a != b) // Structural inequality
println(a === b) // Referential equality
println(a > b) // Greater than
println(a < b) // Less than
println(a >= b) // Greater than or equal
println(a <= b) // Less than or equal
Logical Operators
Kotlin
1234567val x = true
val y = false
println(x && y) // Logical AND
println(x || y) // Logical OR
println(!x) // Logical NOT
Control Structures
Conditional Statements
Kotlin
1234567891011121314151617181920212223242526// If-Else (an expression in Kotlin)
val max = if (x > y) x else y
// When Expression (advanced switch)
when (x) {
1 -> println("x is 1")
2, 3 -> println("x is 2 or 3")
in 4..10 -> println("x is between 4 and 10")
is Int -> println("x is an Int")
else -> println("x is something else")
}
// When without argument (replaces if-else chains)
when {
x < 0 -> println("negative")
x == 0 -> println("zero")
else -> println("positive")
}
// Guard conditions in when (stable since Kotlin 2.1)
when (animal) {
is Cat if animal.mousesCaught > 0 -> println("Successful hunter")
is Cat -> println("Just a cat")
else -> println("Not a cat")
}
Loops
Kotlin
12345678910111213141516171819202122232425262728293031323334353637// For Loop with ranges
for (i in 1..5) println(i) // 1, 2, 3, 4, 5 (closed range)
for (i in 1..<5) println(i) // 1, 2, 3, 4 (open-ended range, since 1.9)
for (i in 5 downTo 1) println(i) // 5..1
for (i in 1..10 step 2) println(i) // 1, 3, 5, 7, 9
// Iterating over collections
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
// With index
for ((index, value) in fruits.withIndex()) {
println("$index: $value")
}
// While Loop
var counter = 0
while (counter < 5) {
println(counter)
counter++
}
// Do-While Loop
do {
println(counter)
counter--
} while (counter > 0)
// Break and Continue
for (i in 1..10) {
if (i == 5) continue
if (i == 8) break
println(i)
}
Functions
Basic Functions
Kotlin
12345678910111213141516171819202122// Function with return type
fun add(a: Int, b: Int): Int {
return a + b
}
// Single-expression function
fun multiply(a: Int, b: Int) = a * b
// Function with default arguments
fun greet(name: String = "World") {
println("Hello, $name!")
}
// Named Arguments
fun createUser(name: String, age: Int = 0, email: String = "") {
// User creation logic
}
createUser(name = "John", email = "john@example.com")
// Vararg parameters
fun sumAll(vararg numbers: Int): Int = numbers.sum()
Lambda Functions
Kotlin
12345678910111213141516// Lambda expression
val sum = { a: Int, b: Int -> a + b }
println(sum(3, 5)) // Prints 8
// Higher-order functions
val numbers = listOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
val filtered = numbers.filter { it % 2 == 0 }
// Function references
fun isOdd(x: Int) = x % 2 != 0
val odds = numbers.filter(::isOdd)
// Trailing lambda syntax
val result = numbers.fold(0) { acc, n -> acc + n }
Object-Oriented Programming
Classes and Objects
Kotlin
1234567891011121314151617181920212223242526272829303132333435363738394041// Basic class with primary constructor
class Person(val name: String, var age: Int) {
fun introduce() {
println("Hi, I'm $name and I'm $age years old")
}
}
// Data Class (automatic equals, hashCode, toString, copy, componentN)
data class User(val id: Int, val username: String)
// Inheritance (classes are final by default)
open class Animal {
open fun makeSound() {
println("Some sound")
}
}
class Dog : Animal() {
override fun makeSound() {
println("Woof!")
}
}
// Singletons via object declaration
object AppConfig {
const val VERSION = "1.0"
}
// Sealed classes / interfaces (exhaustive when)
sealed interface Result<out T> {
data class Success<T>(val value: T) : Result<T>
data class Failure(val error: Throwable) : Result<Nothing>
}
// Value classes (stable since Kotlin 1.5) for zero-cost wrappers
@JvmInline
value class UserId(val value: Long)
// Data objects (stable since Kotlin 1.9) — singletons with proper toString
data object Loading
Extension Functions
Kotlin
12345678910// Add methods to existing classes
fun String.removeWhitespace(): String =
this.replace("\\s".toRegex(), "")
val cleanString = "Hello World".removeWhitespace()
// Extension property
val String.firstChar: Char?
get() = if (isNotEmpty()) this[0] else null
Error Handling
Kotlin
1234567891011121314151617181920// Try-Catch (also an expression)
val result = try {
10 / divisor
} catch (e: ArithmeticException) {
println("Cannot divide by zero")
0
} finally {
println("Cleanup code")
}
// Precondition functions
fun validateAge(age: Int) {
require(age >= 0) { "Age cannot be negative" }
check(state.isReady) { "Not ready" }
}
// Result type for functional error handling
val parsed: Result<Int> = runCatching { "42".toInt() }
parsed.onSuccess { println(it) }.onFailure { println(it.message) }
File I/O
Kotlin
1234567891011121314151617181920import java.io.File
import kotlin.io.path.Path
import kotlin.io.path.readText
import kotlin.io.path.writeText
// Reading a file
val content = File("example.txt").readText()
// Writing to a file
File("output.txt").writeText("Hello, Kotlin!")
// Using Buffered Reader
File("example.txt").bufferedReader().use { reader ->
val lines = reader.readLines()
}
// kotlin.io.path API (stable since Kotlin 1.5)
Path("example.txt").readText()
Path("output.txt").writeText("Hello, Kotlin!")
Coroutines (Asynchronous Programming)
Kotlin
123456789101112131415161718192021222324252627282930313233343536373839import kotlinx.coroutines.*
// Basic Coroutine
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
// Async/Await for parallel decomposition
suspend fun fetchUserData(): String = withContext(Dispatchers.IO) {
delay(1000)
"User Data"
}
suspend fun loadProfile() = coroutineScope {
val user = async { fetchUserData() }
val prefs = async { fetchPreferences() }
user.await() to prefs.await()
}
// Structured concurrency with custom scope
class MyService : CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default)
// Flows for reactive streams
import kotlinx.coroutines.flow.*
fun numbers(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
// StateFlow / SharedFlow are the recommended hot streams
val state = MutableStateFlow(0)
Common Libraries and Frameworks
Standard Library
kotlin.collections: Enhanced collection utilitieskotlin.text: String manipulationkotlin.io/kotlin.io.path: File and I/O operationskotlin.time:DurationandTimeSourceAPIs (stable)
Popular Frameworks
- Spring Boot: First-class Kotlin support for enterprise apps
- Ktor: Lightweight Kotlin-first server and client framework
- Android Development: Kotlin is Google's preferred language for Android
- Jetpack Compose / Compose Multiplatform: Declarative UI for Android, Desktop, iOS, and Web
- Gradle Kotlin DSL: Build automation (default for new Gradle projects)
- kotlinx.serialization: Multiplatform serialization
- kotlinx.coroutines: Structured concurrency
- Exposed / Ktorm: SQL frameworks
Best Practices
Code Style
- Use meaningful variable and function names
- Prefer immutability (
valovervar) - Utilize type inference where it improves readability
- Leverage null safety features instead of
!! - Prefer expression bodies for short functions
- Use
data classfor value-holding types andsealedhierarchies for closed type sets
Performance Tips
- Use
inlinefunctions for higher-order functions with reified type params - Prefer
Sequencefor large or chained collection operations - Use
@JvmInline value classfor zero-cost type-safe wrappers - Minimize object creation in performance-critical code
- Use
buildList/buildStringfor incremental construction
Testing
Kotlin
1234567891011121314151617181920// JUnit 5 Example
import kotlin.test.Test
import kotlin.test.assertEquals
class CalculatorTest {
@Test
fun `addition works correctly`() {
assertEquals(5, 2 + 3)
}
}
// Coroutine testing with kotlinx-coroutines-test
import kotlinx.coroutines.test.runTest
@Test
fun coroutineTest() = runTest {
val value = fetchUserData()
assertEquals("User Data", value)
}
Recent Language Highlights
- K2 compiler is the default since Kotlin 2.0 — faster builds and better diagnostics
- Open-ended ranges with
..<operator - Data objects for singleton sealed-hierarchy members
- Guard conditions in
whenexpressions - Stable Kotlin Multiplatform,
kotlin.time.Duration, andkotlin.io.path - Context parameters (Beta) replacing the experimental
context receivers - kapt is in maintenance mode; prefer KSP (Kotlin Symbol Processing) for annotation processing
Resources for Further Learning
- Official Kotlin Documentation: https://kotlinlang.org/docs/
- Kotlin Koans: Online interactive tutorials
- JetBrains Academy Kotlin track
- JetBrains Kotlin YouTube Channel
- Books: "Kotlin in Action, Second Edition", "Atomic Kotlin", "Programming Kotlin"
Multiplatform Development
Kotlin Multiplatform (stable) supports sharing code across:
- JVM (server, desktop)
- Android
- iOS (via Kotlin/Native)
- JavaScript / Wasm (browser and Node.js)
- Native targets (macOS, Windows, Linux)
Compose Multiplatform extends Jetpack Compose to share UI across Android, iOS, Desktop, and Web.
Conclusion
Kotlin offers a modern, concise, and safe programming experience with seamless Java interoperability, powerful language features, and a mature multiplatform story powered by the K2 compiler.
Continue Learning
Discover more cheatsheets to boost your productivity