Kotlin Tip #26: Use error() to indicate unreachable code points — 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readMar 6, 2024

--

Twitter | LinkedIn | YouTube | Instagram
Tip #25: Use check() for precondition validation in your code

When developing your application, it is essential to clearly communicate the intentions behind every piece of code. One often overlooked aspect is the explicit marking of code regions that are theoretically unreachable. Kotlin, aiming at enhancing code clarity and safety, offers a function for this purpose: error().

The error() function in Kotlin is a straightforward way to throw an IllegalStateException, signaling that a particular piece of code was not supposed to be executed. The function takes a single argument—a message string—that should ideally explain why this code path is considered invalid.

By using error(), the code clearly communicates to other developers (and your future self) that a specific block of code is considered unreachable. It's a form of self-documenting code. Besides that, in case the unreachable code is executed due to a bug or a logical error, error() immediately halts the execution, preventing the application from entering an invalid state.

Consider an application that processes user commands. Each command corresponds to a specific action, but what if, due to a bug, an undefined command is received?

fun processCommand(command: String) {
when (command) {
"start" -> startProcess()
"stop" -> stopProcess()
"pause" -> pauseProcess()
else -> error("Received an undefined command: $command")
}
}

In the example above, the else branch of the when expression uses error() to indicate that this code should not be reachable if all commands are accounted for. If a new command is introduced and not properly handled, this error() call will immediately highlight the oversight.

By employing the error() function to mark and handle unreachable code points, you elevate your Kotlin code's clarity, safety, and maintainability. It's a testament to Kotlin's commitment to empowering developers to write expressive and idiomatic code, focusing on clear communication of intent and preemptive error handling.

I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #27: Use require() for argument validation in functions or constructors

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--