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
    }
}
StringUtil.countAmountOfX("xSamplex")

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

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

2. Avoid if-null check

//Don't
if (order == null || order.customer == null || order.customer.address == null){
    throw IllegalArgumentException("Invalid Order")
}
val city = order.customer.address.city

//Do
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

//Don't
if (service !is CustomerService) {
    throw IllegalArgumentException("No CustomerService")
}
service.getCustomer()

//Do
service as? CustomerService ?: throw IllegalArgumentException("No CustomerService")
service.getCustomer()

4. Avoid not-null Assertions

//Don't
order!!.customer!!.address!!.city

5. Consider let

Sometimes using let can be a concise alternative for if

val order: Order? = findOrder()
if (order != null){
    dun(order.customer)
}

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

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