A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull request.
provides a Customer
class with the following functionality:
equals()
hashCode()
toString()
copy()
component1()
, component2()
, …, for all properties (see Data classes)Or alternatively, even shorter:
k
, v
can be called anything.
for (i in 1..100) { ... } // closed range: includes 100 for (i in 1 until 100) { ... } // half-open range: does not include 100 for (x in 2..10 step 2) { ... } for (x in 10 downTo 1) { ... } if (x in 1..10) { ... }
val value = ... val mapped = value?.let { transformValue(it) } ?: defaultValue // defaultValue is returned if the value or the transform result is null.
fun transform(color: String): Int { return when (color) { "Red" -> 0 "Green" -> 1 "Blue" -> 2 else -> throw IllegalArgumentException("Invalid color param value") } }
fun test() { val result = try { count() } catch (e: ArithmeticException) { throw IllegalStateException(e) } // Working with result }
fun foo(param: Int) { val result = if (param == 1) { "one" } else if (param == 2) { "two" } else { "three" } }
Unit
This is equivalent to
This can be effectively combined with other idioms, leading to shorter code. E.g. with the when-expression:
fun transform(color: String): Int = when (color) { "Red" -> 0 "Green" -> 1 "Blue" -> 2 else -> throw IllegalArgumentException("Invalid color param value") }
with
)class Turtle { fun penDown() fun penUp() fun turn(degrees: Double) fun forward(pixels: Double) } val myTurtle = Turtle() with(myTurtle) { //draw a 100 pix square penDown() for (i in 1..4) { forward(100.0) turn(90.0) } penUp() }
apply
)This is useful for configuring properties that aren't present in the object constructor.
val stream = Files.newInputStream(Paths.get("/some/file.txt")) stream.buffered().reader().use { reader -> println(reader.readText()) }
// public final class Gson { // ... // public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException { // ... inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)
Kotlin's standard library has a TODO()
function that will always throw a NotImplementedError
. Its return type is Nothing
so it can be used regardless of expected type. There's also an overload that accepts a reason parameter:
fun calcTaxes(): BigDecimal = TODO("Waiting for feedback from accounting")
IntelliJ IDEA's kotlin plugin understands the semantics of TODO()
and automatically adds a code pointer in the TODO toolwindow.
© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/reference/idioms.html