Kotlin tips – #day2

1. Top-Level (Extensions) Functions for Utility Functions

// Don't
object StringUtil {
    fun countAmountOfX(string: String): Int{
        return string.length - string.replace("x", "").length

// Do
fun String.countAmountOfX(): Int {
    return length - replace("x", "").length

This way, our code feels more like telling a story.

2. Avoid if-null check

if (order == null || order.customer == null || order.customer.address == null){
    throw IllegalArgumentException("Invalid Order")
val city = order.customer.address.city

val city = order?.customer?.address?.city ?: throw IllegalArgumentException("Invalid Order")

Often you can use null-safe call ?. or the elvis operator ?: instead.

3. Avoid if-type check

if (service !is CustomerService) {
    throw IllegalArgumentException("No CustomerService")

service as? CustomerService ?: throw IllegalArgumentException("No CustomerService")

4. Avoid not-null Assertions


5. Consider let

Sometimes using let can be a concise alternative for if

val order: Order? = findOrder()
if (order != null){

// Do
findOrder()?.let { dun(it.customer) }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s