https://kotlinlang.org/docs/reference/idioms.html#string-interpolation
Code Block println("Name $name")
Prefer read-only `val` over mutable `var`
Code Block /* bad */ var counter = 0 for(i in 0..20){ counter += i } /* preferred */ val sum = (0..20).sum()
Unit as a return type
Code Block fun doSomething(): Unit{ println("do something") }
https://kotlinlang.org/docs/reference/idioms.html#single-expression-functions
Code Block fun theAnswer() = 42
https://kotlinlang.org/docs/reference/idioms.html#default-values-for-function-parameters
Code Block fun foo(a: Int = 0, b: String = "") { ... }
https://kotlinlang.org/docs/reference/idioms.html#creating-a-singleton
Code Block object Resource { val name = "Name" }
https://kotlinlang.org/docs/reference/idioms.html#instance-checks
Code Block when (x) { is Foo -> ... is Bar -> ... else -> ... }
https://kotlinlang.org/docs/reference/idioms.html#creating-dtos-pojospocos
Code Block data class Customer(val name: String, val email: String)
Use the fact that `return` and `throw` have type `Nothing`, https://kotlinlang.org/docs/reference/idioms.html#todo-marking-code-as-incomplete
Code Block val x = foo() ?: return notFound() val y = if(conditionSatisfied()){ 1.0 } else { error("Condition is not satisfied"}//throws inside, the type is Nothing }
Nullable truth.
Code Block a?.b == true //instead of a?.b ?: false
Safe chain and elvis (https://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand)
Code Block val files = File("Test").listFiles() println(files?.size ?: "empty")
https://kotlinlang.org/docs/reference/idioms.html#execute-if-not-null
Code Block val value = ... value?.let { ... // execute this block if not null }
https://kotlinlang.org/docs/reference/idioms.html#extension-functions
Code Block fun String.spaceToCamelCase() { ... } "Convert this to camelcase".spaceToCamelCase()
Extension properties
Code Block import java.util.Calendar var Calendar.year get() = get(Calendar.YEAR) set(value) = set(Calendar.YEAR, value) val calendar = Calendar.getInstance() println(calendar.year) // 2020 calendar.year = 2021 println(calendar.year) // 2021
- With block
- Companion object
https://kotlinlang.org/docs/reference/idioms.html#checking-element-presence-in-a-collection
...