zsmb.coHot off the keys



Announcing requireKTX

2021.06.17. 18h • 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!



You might also like...

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.

Compose O'Clock

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.

Pi Practice App in Compose

In another detailed Jetpack Compose walkthrough, we'll look at implementing a simple app for practicing the digits of pi!

Sealed goodies coming in Kotlin 1.5

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!