2021.06.17. 18h • Márton Braun
So, I got tired of writing code like this.
And seeing others have to write code like this:
val channelType: String = inputData.getString(DATA_CHANNEL_TYPE)!! val channelId: String = inputData.getString(DATA_CHANNEL_ID)!! val messageId: String = inputData.getString(DATA_MESSAGE_ID)!!
So I created requireKTX.
What does it do?
It adds extensions so that the code above becomes this:
val channelType: String = inputData.requireString(DATA_CHANNEL_TYPE) val channelId: String = inputData.requireString(DATA_CHANNEL_ID) val messageId: String = inputData.requireString(DATA_MESSAGE_ID)
These extensions exist on various types (
Data), and for various types of data you’d want to fetch (
Int, and dozens more).
Instead of giving you nullable types or default values, they’ll throw meaningful exceptions (
IllegalArgumentException) with nicely worded error messages describing why the value couldn’t be fetched.
You also get nicer
getOrNull style methods for all these base types and all types you’d want to fetch, so that the possible nullability is explicit:
val userId: String? = requireArguments().getStringOrNull("user_id")
Check out the library on GitHub, give it a star ⭐, add it to your project, send feedback my way!
You might also like...
In another detailed Jetpack Compose walkthrough, we'll look at implementing a simple app for practicing the digits of pi!
I started learning Jetpack Compose this week. Two days into that adventure, here's a quick look at how a neat clock design can be built up in Compose, step-by-step.
Kotlin 1.5 will bring exciting new features, among them improvements to sealed classes and an introduction of sealed interfaces. Let's take a look at what that will look like!
Let's send this one off so that we can get started on a better one. The "usual" recap of what I've done this year.