ylliX - Online Advertising Network

Announcing requireKTX


2021-06-17

Márton Braun

So, I got tired of writing code like this.

requireArguments().getString("user_id")!!

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:

requireArguments().requireString("user_id")

And 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 (Bundle, Intent, WorkManager Data), and for various types of data you’d want to fetch (String, Int, and dozens more).

Instead of giving you nullable types or default values, they’ll throw meaningful exceptions (IllegalStateException or IllegalArgumentException) with nicely worded error messages describing why the value couldn’t be fetched.

Bonus

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")

That’s all!

Check out the library on GitHub, give it a star ⭐, add it to your project, send feedback my way!


Follow me to keep in touch and get notified of similar posts!


You might also like…

All About Opt-In Annotations

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.

The conflation problem of testing StateFlows

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.

Wrap-up 2021

Another year over, a new one’s almost begun. Here’s a brief summary of what I’ve done in this one.

A Bit of Gradle Housekeeping

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.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *