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...
Another year over, a new one's almost begun. Here's a brief summary of what I've done in this one.
While cleaning is traditionally a spring activity, let me invite you to do it at the end of summer this time around. In this article, we'll take a look at some Gradle configuration that you can probably clean up in your Android project.
StateFlow behaves as a state holder and a Flow of values at the same time. Due to conflation, a collector of a StateFlow might not receive all values that it holds over time. This article covers what that means for your tests.
Have you ever encountered APIs that show warnings or errors when you use them, saying that they're internal or experimental? In this guide, you'll learn everything you need to know about opt-in APIs in Kotlin: how to create and use them, and all their nuances.