Kotlin Tips and Tricks to Elevate Your Code Readability

ndriqa
3 min readSep 22, 2023

--

As an Android developer primarily working with Kotlin, I’ve found the language to be a refreshing upgrade from traditional Java. With its concise syntax, Kotlin is inherently more readable. However, as with any language, there are always ways to enhance code clarity. Here, I’d like to share some tricks I’ve picked up, aiming to further elevate your Kotlin code’s readability. 🚀

Use the when Expression:

The when expression can be more readable than lengthy if-else chains. Especially in situations where you have multiple conditions, it streamlines the logic. For example:

val weatherReport = when (degreeInCelsius) {
-273 -> "Icer than ice"
in -272..0 -> "Cool cool cool cool"
in 1..20 -> "Chilly"
in 21..41 -> "Hot"
42 -> "Life"
else -> "HOT hot"
}

Leverage Extension Functions:

This is one of my favorite Kotlin features. Extension functions allow you to add functions to existing types without modifying them. This can reduce boilerplate and make code more intuitive. For instance, consider an extension function for a String to check if it's a strong password(which in real life would be done on the backend side, but for demonstration purposes):

fun String.isStrongPassword(): Boolean {
// check length
// check symbols and numbers
// check strength
// check any other stuff
// return result
}

Then, when we need to use it, it becomes a feast for the eyes:

val isPasswordStrongEnough = userPasswordInput.isStrongPassword()

Opt for Kotlin’s Standard Functions:

Functions like apply, run, let, also, and with can be powerful tools when used right. For instance, apply is perfect when configuring an object:

val dialog = AlertDialog.Builder(this).apply {
setTitle("Alert!")
setMessage("This is an alert dialog.")
}.create()

It’s important to know when to use which one of them since each of them has distinct use cases and is built to return different objects

Keep an eye on Null Safety with Safe Calls (?.) and the Elvis Operator (?:):

Kotlin’s null safety features have saved me from countless potential null pointer exceptions to the point that when reading Java code, my mind automatically thinks: “Actually, that one could be null”, then my subconscious mocks my brain like “AcTuAllY 🤓”. Anyway, use ?. to safely call a method or access a property, and pair it with ?: to provide a default value if necessary:

val userHeight = user?.body?.physicalProperties?.height ?: 0

Use Destructuring Declarations for Multi-Returns:

Instead of creating an entire data class just to return multiple values, Kotlin lets you return multiple values from a function, which can be immediately restructured:

fun getUserInfo(): Pair<String, Int> = Pair("Alice", 30)
val (name, age) = getUserInfo()

In Conclusion:

The path to writing clean, elegant, and readable code in Kotlin is filled with many helpful tools and tricks. My journey from crafting Android apps to occasionally dabbling in Jetpack Compose for Desktop has made me appreciate Kotlin even more. Remember, the key isn’t just writing code that works, but code that’s easily understood by others, and even by your future self. One quote that has stuck with me since the start of my programming career is the one by Martin Fowler: “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”. Now, I get that writing code that computers can understand is sufficient enough, in terms of getting the job done for now, however, only you working on that piece of code is almost never the case in the industry, where you probably won't even be working on only one project for long. Someone else has to read, understand, and modify your code. Basically, treat your code how you want others' code to treat you!

Keep pushing, keep shining, and always give it everything! 🌟

--

--