A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull request.
data class Customer(val name: String, val email: String)
provides a Customer
class with the following functionality:
- getters (and setters in case of var{: .keyword }s) for all properties
equals()
hashCode()
toString()
copy()
component1()
,component2()
, ..., for all properties (see Data classes)
fun foo(a: Int = 0, b: String = "") { ... }
val positives = list.filter { x -> x > 0 }
Or alternatively, even shorter:
val positives = list.filter { it > 0 }
println("Name $name")
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
for ((k, v) in map) {
println("$k -> $v")
}
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 list = listOf("a", "b", "c")