๐Ÿ…บ

Kotlin Cheat Sheet

Google's preferred language for Android development โ€” runs on the JVM alongside Java, but with modern conveniences like null safety built directly into the type system. Copy-paste examples plus live Run/Submit exercises.

Jump to: Your first programVariablesNull safety if / elseLoopsData classes ๐Ÿš€ Practice problems

Your first program

fun main() {
    println("Hello, world!")
}

Variables

val age = 25          // val = constant, can't change
var name = "Sam"      // var = can change
val price: Double = 19.99

Null safety

Kotlin's headline feature โ€” the type system tracks whether a value can be null, so a whole class of crashes gets caught at compile time.

var middleName: String? = null   // the ? means "this can be null"

val length = middleName?.length ?: 0   // safe call + default fallback
println(length)

if / else

val age = 20
if (age >= 18) {
    println("Adult")
} else if (age >= 13) {
    println("Teen")
} else {
    println("Child")
}

Loops

for (i in 0 until 5) {
    println(i)
}

var n = 3
while (n > 0) {
    println(n)
    n--
}

Data classes

Kotlin generates equals/hashCode/toString for you automatically for simple data holders.

data class Dog(val name: String, val age: Int) {
    fun bark() {
        println("$name says woof!")
    }
}

// val d = Dog("Rex", 3); d.bark()

๐Ÿš€ Practice problems

Full runnable programs, compiled and run in a real Kotlin sandbox โ€” same workspace as the other cheat sheets.

Sum a list EASY

fun main() {
    val nums = listOf(4, 8, 15, 16, 23, 42)
    println(nums.sum())
}

Reverse a string MEDIUM

fun main() {
    val s = "kotlin"
    println(s.reversed())
}

FizzBuzz MEDIUM

fun main() {
    for (i in 1..15) {
        when {
            i % 15 == 0 -> println("FizzBuzz")
            i % 3 == 0 -> println("Fizz")
            i % 5 == 0 -> println("Buzz")
            else -> println(i)
        }
    }
}

Word frequency with a map HARD

fun main() {
    val text = "the cat sat on the mat the cat ran"
    val counts = mutableMapOf<String, Int>()
    for (word in text.split(" ")) {
        counts[word] = (counts[word] ?: 0) + 1
    }
    for ((word, n) in counts) {
        println("$word: $n")
    }
}