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")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map["key"])
map["key"] = value
val p: String by lazy {
// compute the string
}
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
object Resource {
val name = "Name"
}
val files = File("Test").listFiles()
println(files?.size)
val files = File("Test").listFiles()
println(files?.size ?: "empty")
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
val data = ...
data?.let {
... // execute this block if not null
}
val data = ...
val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull
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"
}
}
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
fun theAnswer() = 42
This is equivalent to
fun theAnswer(): Int {
return 42
}
This can be effectively combined with other idioms, leading to shorter code. E.g. with the when{: .keyword }-expression:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
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()
}
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)
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}