glunty

Kotlin Cheat Sheet

A searchable reference of core Kotlin syntax and what each piece does.

Common Kotlin syntax with a plain-English description of what each piece does
Snippet What it does
fun main() { println("Hello, world!") } Program entry point that runs when the app starts.
println("Hello") Print a line of text to standard output followed by a newline.
val x = 5 Declare a read-only (immutable) variable that cannot be reassigned.
var count = 0 Declare a mutable variable that can be reassigned later.
val n: Int = 42 Declare a 32-bit integer with an explicit type.
val s: String = "hi" Declare a string of text.
val ok: Boolean = true Declare a true or false value.
val d: Double = 3.14 Declare a 64-bit floating-point number.
val name = "Kotlin" Let the compiler infer the type from the value, so no annotation is needed.
println("Hi, $name") Insert a variable into a string with a dollar sign (string template).
println("Sum: ${a + b}") Insert an expression into a string using a dollar sign and braces.
const val PI = 3.14 Declare a compile-time constant usable in annotations and top-level code.
// line comment Write a single-line comment ignored by the compiler.
/* block comment */ Write a multi-line comment ignored by the compiler.
val name: String? = null Allow a variable to hold a value or null using a trailing question mark.
val len = name?.length Access a member only when the receiver is not null, returning null otherwise (safe call).
val len = name?.length ?: 0 Provide a fallback value used when the left side is null (elvis operator).
val len = name!!.length Assert a nullable is not null, throwing an exception if it is (not-null assertion).
name?.let { println(it) } Run a block only when the value is not null, referring to it as it.
lateinit var repo: Repo Declare a non-null property that is initialized later before first use.
val n = obj as? Int Cast to a type, returning null instead of throwing when it does not fit (safe cast).
val nums = listOf(1, 2, 3) Create a read-only list of the given items.
val nums = mutableListOf(1, 2) Create a list you can add to and remove from.
val m = mapOf("a" to 1) Create a read-only map of key to value pairs.
val s = setOf(1, 2, 2) Create a read-only set that drops duplicate values.
nums.forEach { println(it) } Run an action once for each element.
val doubled = nums.map { it * 2 } Transform each element into a new list.
val evens = nums.filter { it % 2 == 0 } Keep only the elements that match a condition.
val sum = nums.reduce { acc, n -> acc + n } Combine all elements into a single accumulated value.
val head = nums.first() Return the first element, throwing if the collection is empty.
val byLen = words.sortedBy { it.length } Return a new list sorted by the selected key.
val max = if (a > b) a else b Use if as an expression that returns a value.
when (x) { 1 -> "one"; else -> "other" } Match a value against several branches, like a switch.
for (n in nums) println(n) Iterate over a range, array, or collection.
while (i < 10) i++ Repeat the body while a condition stays true.
do { i++ } while (i < 10) Run the body once, then repeat while the condition holds.
for (i in 1..5) println(i) Create an inclusive range from 1 to 5.
val r = 10 downTo 1 step 2 Count down with a custom step between values.
break Exit the nearest enclosing loop immediately.
continue Skip to the next iteration of the loop.
fun add(a: Int, b: Int): Int { return a + b } Declare a function with typed parameters and a return type.
fun pow(base: Int, exp: Int = 2): Int = base * exp Give a parameter a default so callers can leave it out.
greet(name = "Sam") Pass arguments by parameter name in any order (named arguments).
fun square(x: Int) = x * x Define the whole body as one expression, without braces or return.
val sum = { a: Int, b: Int -> a + b } Define an anonymous function value you can pass around (lambda).
fun apply(x: Int, f: (Int) -> Int) = f(x) Take a function as a parameter or return one (higher-order function).
fun String.shout() = this.uppercase() Add a new method to an existing type (extension function).
infix fun Int.times(s: String) = s.repeat(this) Call a single-argument method without a dot or parentheses (infix).
fun sumAll(vararg n: Int) = n.sum() Accept a variable number of arguments of one type (vararg).
class Dog Declare a class; create an instance by calling it like a function.
class Dog(val name: String, val age: Int) Declare a primary constructor whose parameters become properties.
data class Point(val x: Int, val y: Int) Auto-generate equals, hashCode, toString, and copy from the properties.
class Box { val size = 10 } Declare a read-only property inside the class body.
open class Animal; class Cat : Animal() Mark a class open so it can be subclassed, then extend it.
override fun speak() = "meow" Replace a member inherited from a superclass.
interface Shape { fun area(): Double } Declare a contract of members that classes must implement.
object Config { val version = 1 } Declare a single shared instance, a built-in singleton.
class Foo { companion object { val ID = 1 } } Hold members tied to the class itself, similar to static members.
sealed class Result Restrict a type to a known, fixed set of subclasses.
enum class Color { RED, GREEN, BLUE } Define a type with a fixed set of named constants.

Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.

What this tool does

This is a searchable quick reference for the Kotlin syntax you reach for every day, from basic variables and string templates to null safety, collections, control flow, functions, and classes. Each row pairs a short snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one topic. The whole list is built into the page, so it works offline and sends nothing anywhere.

How to use it

Start typing in the Filter box. Entering elvis jumps straight to the ?: operator; entering null surfaces the null-safety rows; entering data class shows how to auto-generate equals and copy. The category buttons (Basics, Null safety, Collections, Control flow, Functions, Classes) narrow the table to one family and combine with the text filter, so you can pick Collections and type filter to zero in on one operation. Clear the box to see the full sheet again.

Common use cases

  • Recalling the exact form of a snippet you use rarely, like a when expression or an infix function.
  • Copying safe, idiomatic Kotlin into your editor instead of guessing at the syntax.
  • Teaching a teammate the difference between val and var, or between a safe call and the !! assertion.
  • Looking up how a data class, sealed class, or companion object is declared.
  • Reviewing core Kotlin syntax before an interview or when switching over from Java.

Common pitfalls

  • Overusing the not-null assertion. The !! operator throws a null pointer exception the moment the value is null, which defeats the point of null safety. Prefer a safe call ?. with an ?: fallback instead.
  • Confusing val with immutability of contents. A val only stops reassignment of the reference. A val pointing at a mutableListOf can still gain and lose items, so choose listOf when you want the contents fixed too.
  • Reading a lateinit before it is set. A lateinit property that is used before assignment throws an uninitialized property exception. Assign it before first use, or make the type nullable instead.
  • Forgetting the else in a when expression. When when is used as an expression that returns a value, it must be exhaustive. Add an else branch, or cover every case of a sealed class or enum so the compiler is satisfied.

Frequently asked questions

What is null safety in Kotlin?
Null safety is a Kotlin feature that separates types that can hold null from types that cannot. A plain String can never be null, while a String with a trailing question mark, written String?, is allowed to be null. The compiler then forces you to handle the null case before you use the value, which prevents most null pointer exceptions at compile time rather than at runtime.
What is a data class?
A data class is a class meant mainly to hold data. When you mark a class with the data keyword, Kotlin automatically generates equals, hashCode, toString, and a copy function from the properties in the primary constructor. That removes a lot of boilerplate, so a simple value type like a point or a user record can be written in a single line.
What is the difference between val and var?
Both declare variables, but val creates a read-only reference that cannot be reassigned after it is set, while var creates a mutable reference you can assign to again. Prefer val by default because immutable references are easier to reason about, and reach for var only when the value genuinely needs to change. Note that val makes the reference constant, not the object it points to, so a val list can still have items added if the list itself is mutable.
What is the elvis operator?
The elvis operator, written ?:, supplies a fallback value when the expression on its left is null. For example, a safe call that might return null can be followed by the elvis operator and a default, so the result is the default instead of null. It is a compact way to unwrap a nullable value while guaranteeing a non-null result.
What is an extension function?
An extension function lets you add a new method to a type you do not own, such as String or a class from a library, without editing its source or subclassing it. You write the receiver type, a dot, and the function name, and inside the body the keyword this refers to the receiver. Extensions are resolved statically and are a clean way to keep helper logic readable at the call site.
Does this cheat sheet send my searches anywhere?
No. The entire Kotlin reference is baked into the page and every search and filter runs locally in your browser with JavaScript, so nothing you type is sent to any server. You can open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.

Embed this tool

Free for any use; attribution appreciated. Paste this on your site:

The embed runs the same tool that lives at this URL. No tracking; no ads inside the embed. Resize height as needed for your layout.

Cite this tool

For academic, journalistic, or technical references. Pick a format:

Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.

Embedded tool from glunty.com