Kotlin Tip #27: Use require() for argument validation in functions or constructors — 100 Kotlin Tips in 100 Days

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

--

Twitter | LinkedIn | YouTube | Instagram
Tip #26: Use error() to indicate unreachable code points

When dealing with functions or constructor that have preconditions for their arguments, it is essential to validate that the input values meet these specific criteria. To achieve this, Kotlin provides the require() function.

The require() function in Kotlin makes sure that only correctly structured data is allowed into your constructors and functions. It checks a condition, and if the condition is not met (meaning it's false), it throws an error called IllegalArgumentException, stopping the program from going any further. This approach helps catch and address mistakes with the data as soon as possible.

Its basic syntax is as follows:

require(condition) { "Error message" }

Here, condition is the boolean expression that must evaluate to true for execution to proceed. The optional lambda { "Error message" } allows you to provide a custom message that can aid in debugging by describing why the requirement failed.

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 #28: Use assert() to assert conditions in development

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

--

--