Some more small tips just for you!

let()

Using let() can be a concise alternative for if . Check out the following code:

val listWithNulls: List<String?> = listOf("A", null)

for (item in listWithNulls) {

if (item != null) {

println(item!!)

}

}

With let() , there is no need for an if .

val listWithNulls: List<String?> = listOf("A", null)

for (item in listWithNulls) {

item?.let { println(it) } // prints A and ignores null

}

when()

when replaces the switch operator of Java and it can also be used to clean up some hard to read if conditions.

// Java

public Product parseResponse(Response response) {

if (response == null) {

throw new HTTPException("Something bad happened");

}

int code = response.code();

if (code == 200 || code == 201) {

return parse(response.body());

}

if (code >= 400 && code <= 499) {

throw new HTTPException("Invalid request");

}

if (code >= 500 && code <= 599) {

throw new HTTPException("Server error");

} throw new HTTPException("Error! Code " + code);

}

And in Kotlin it would look like:



fun parseResponse(response: Response?) = when (response?.code()) {

null -> throw HTTPException("Something bad happened")

200, 201 -> parse(response.body())





else -> throw HTTPException("Error! Code ${response.code()}")

} // Kotlinfun parseResponse(response: Response?) = when (response?.code()) {null -> throw HTTPException("Something bad happened")200, 201 -> parse(response.body()) in 400..499 -> throw HTTPException("Invalid request") in 500..599 -> throw HTTPException("Server error")else -> throw HTTPException("Error! Code ${response.code()}")

Read-only lists, maps, …

Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc). Precise control over exactly when collections can be edited is useful for eliminating bugs, and for designing good APIs.

The Kotlin standard library contains utility functions and types for both mutable and immutable collections. For example listOf() , and mutableListOf() .

val list = listOf(“a”, “b”, “c”) val map = mapOf("a" to 1, "b" to 2, "c" to 3)

Lazy property

lazy is good, use it when it makes sense! Keeping a low memory footprint is a good use case, and also saving CPU cycles if its initialization is expensive.

Lazy properties only get computed upon first access.