kotlin-idioms.md

#Idioms

Last modified: 07 July 2025

A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull request.


#Create DTOs (POJOs/POCOs)

kotlindata class Customer(val name: String, val email: String)

Provides a Customer class with the following functionality:

#Default values for function parameters

kotlinfun foo(a: Int = 0, b: String = "") { ... }

#Filter a list

kotlinval positives = list.filter { x -> x > 0 }

Or alternatively, even shorter:

kotlinval positives = list.filter { it > 0 }

#Check the presence of an element in a collection

kotlinif ("john@example.com" in emailsList) { ... }

if ("jane@example.com" !in emailsList) { ... }

#String interpolation

kotlinprintln("Name $name")

#Read standard input safely

kotlin// Reads a string and returns null if the input can't be converted into an integer.
val wrongInt = readln().toIntOrNull()
println(wrongInt) // null

// Reads a string that can be converted into an integer and returns an integer.
val correctInt = readln().toIntOrNull()
println(correctInt) // 13

#Instance checks

kotlinwhen (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}

#Read-only list

kotlinval list = listOf("a", "b", "c")

#Read-only map

kotlinval map = mapOf("a" to 1, "b" to 2, "c" to 3)

#Access a map entry

kotlinprintln(map["key"])
map["key"] = value

#Traverse a map or a list of pairs

kotlinfor ((k, v) in map) {
    println("$k -> $v")
}

k and v can be any convenient names, such as name and age.

#Iterate over a range

kotlinfor (i in 1..100) { ... }  // closed-ended range: includes 100
for (i in 1..<100) { ... } // open-ended range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
(1..10).forEach { ... }

#Lazy property

kotlinval p: String by lazy {
    // the value is computed only on first access
    // compute the string
}

#Extension functions

kotlinfun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

#Create a singleton

kotlinobject Resource {
    val name = "Name"
}

#Use inline value classes for type-safe values

kotlin@JvmInline
value class EmployeeId(private val id: String)

@JvmInline
value class CustomerId(private val id: String)

If you accidentally mix up EmployeeId and CustomerId, a compilation error is triggered.

#Instantiate an abstract class

kotlinabstract class MyAbstractClass {
    abstract fun doSomething()
    abstract fun sleep()
}

fun main() {
    val myObject = object : MyAbstractClass() {
        override fun doSomething() {
            // ...
        }

        override fun sleep() { // ...
        }
    }
    myObject.doSomething()
}

#If-not-null shorthand

kotlinval files = File("Test").listFiles()

println(files?.size) // size is printed if files is not null

#If-not-null-else shorthand

kotlinval files = File("Test").listFiles()

// For simple fallback values:
println(files?.size ?: "empty")

// To calculate a more complicated fallback value in a code block, use `run`
val filesSize = files?.size ?: run {
    val someSize = getSomeSize()
    someSize * 2
}
println(filesSize)

#Execute an expression if null

kotlinval values = ...
val email = values["email"] ?: throw IllegalStateException("Email is missing!")

#Get first item of a possibly empty collection

kotlinval emails = ... // might be empty
val mainEmail = emails.firstOrNull() ?: ""

#Execute if not null

kotlinval value = ...

value?.let {
    ... // execute this block if not null
}

#Map nullable value if not null

kotlinval value = ...

val mapped = value?.let { transformValue(it) } ?: defaultValue

#Return on when statement

kotlinfun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

#try-catch expression

kotlinfun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }
}

#if expression

kotlinval y = if (x == 1) {
    "one"
} else if (x == 2) {
    "two"
} else {
    "other"
}

#Builder-style usage of methods that return Unit

kotlinfun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

#Single-expression functions

kotlinfun theAnswer() = 42

Equivalent to:

kotlinfun theAnswer(): Int {
    return 42
}

#Call multiple methods on an object instance (with)

kotlinval myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
    penDown()
    for (i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}

#Configure properties of an object (apply)

kotlinval myRectangle = Rectangle().apply {
    length = 4
    breadth = 5
    color = 0xFAFAFA
}

#Java 7's try-with-resources

kotlinval stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}

#Generic function that requires reified type information

kotlininline fun <reified T: Any> Gson.fromJson(json: JsonElement): T =
    this.fromJson(json, T::class.java)

#Swap two variables

kotlinvar a = 1
var b = 2
a = b.also { b = a }

#Mark code as incomplete (TODO)

Kotlin's standard library has a TODO() function that will always throw a NotImplementedError. Its return type is Nothing.

kotlinfun calcTaxes(): BigDecimal = TODO("Waiting for feedback from accounting")