Kotlin Cheat Sheet

Variables and Data Types

Kotlin has two types of variables: val (immutable) and var (mutable).

val name: String = "Kotlin"
var age: Int = 25

Type Inference

Explicit type declaration is optional when the compiler can infer it.

val message = "Hello"
var count = 10

Null Safety

Kotlin enforces null safety at compile time using nullable types.

var name: String? = null

String Templates

Embed variables and expressions in strings using $ and ${}.

val name = "World"
println("Hello, $name!")

Control Flow (if, when, loops)

if Expression

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

when Expression

when (x) {
  1 -> println("One")
  else -> println("Other")
}

Loops

for (i in 1..5) {
  println(i)
}

Functions and Parameters

fun greet(name: String): String {
  return "Hello, $name"
}

Default and Named Arguments

fun greet(name: String = "Guest") {
  println("Hello, $name")
}

fun main() {
  greet()             // uses default
  greet(name = "Sam") // named argument
}

Lambdas and Higher-Order Functions

val sum = { a: Int, b: Int -> a + b }
fun operate(x: Int, y: Int, op: (Int, Int) -> Int): Int = op(x, y)

Inline Functions

inline fun operate(a: Int, b: Int, func: (Int, Int) -> Int): Int {
  return func(a, b)
}

Classes and Objects

class Person(val name: String) {
  fun greet() = println("Hello, $name")
}

Constructors (Primary and Secondary)

class Person(val name: String) {
  constructor(name: String, age: Int): this(name)
}

Inheritance and Overriding

open class Animal {
  open fun sound() = println("...")
}

class Dog: Animal() {
  override fun sound() = println("Bark")
}

Visibility Modifiers

Modifiers: public, internal, protected, private

private class Secret

Data Classes

data class User(val name: String, val age: Int)

Singleton (object keyword)

object Logger {
  fun log(msg: String) = println(msg)
}

Lists, Sets, and Maps

val numbers = listOf(1, 2, 3)
val mutableNumbers = mutableListOf(1, 2, 3)
val uniqueItems = setOf("a", "b")
val mapping = mapOf("key" to "value")

Collection Functions (map, filter, reduce, etc.)

val nums = listOf(1, 2, 3, 4)
val evens = nums.filter { it % 2 == 0 }
val doubled = nums.map { it * 2 }
val total = nums.reduce { acc, i -> acc + i }

Mutable vs Immutable Collections

listOf, setOf, and mapOf create immutable collections. Use mutableListOf, etc. for mutable ones.

Extension Functions and Properties

fun String.shout(): String = this.uppercase() + "!"
println("hello".shout())

Safe Call, Elvis, Not-null, Scope Functions

val name: String? = null
val length = name?.length           // Safe call
val len = name?.length ?: 0         // Elvis operator
val forced = name!!.length          // Not-null assertion

name?.let { println(it) }           // let
name?.run { println(this) }        // run
name?.also { println(it) }         // also
name?.apply { println(this) }      // apply

Functional Programming

Immutability

Prefer val over var and avoid mutation.

Function Types

val f: (Int, Int) -> Int = { x, y -> x + y }

Closures

fun counter(): () -> Int {
  var count = 0
  return { ++count }
}

Standard Library

String Operations

"kotlin".reversed()
"abc".uppercase()

Ranges and Progressions

for (i in 1..5) { }
for (j in 5 downTo 1 step 2) { }

Destructuring Declarations

val (a, b) = Pair(1, 2)

Pairs and Triples

val pair = Pair("x", 1)
val triple = Triple("x", 1, true)

Exception Handling

try {
  val result = riskyOp()
} catch (e: Exception) {
  println("Error: ${e.message}")
} finally {
  println("Done")
}

Custom Exceptions

class MyException(message: String): Exception(message)

Coroutines (Basics)

suspend Functions

suspend fun fetchData(): String {
  delay(1000)
  return "Data"
}

CoroutineScope and Builders

CoroutineScope(Dispatchers.IO).launch {
  val data = fetchData()
  println(data)
}

Dispatchers

Dispatchers.Default
Dispatchers.IO
Dispatchers.Main

Miscellaneous

Type Aliases

typealias ClickHandler = (Int) -> Unit

Sealed Classes

sealed class Result
class Success(val data: String): Result()
class Error(val exception: Throwable): Result()

Enums

enum class Direction {
  NORTH, SOUTH, EAST, WEST
}

Annotations

@Deprecated("Use newFunc")
fun oldFunc() { }

Generics

class Box(val item: T)

Smart Casts

fun demo(x: Any) {
  if (x is String) {
    println(x.length) // smart cast to String
  }
}