A collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android.

Overview

requireKTX

requireKTX is a collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android, using the same idea as requireContext, requireArguments, and other similar Android SDK methods.

Types that requireKTX provides extensions for:

Why?

Take the example of grabbing a Fragment argument bundle and reading a String ID from it that should always be there: you have two choices, and none of them are great:

// Providing no default value
// Results in a nullable return type, caller has to do null handling
val id: String = requireArguments().getString("user_id")!!

// Providing a (meaningless) default value
// Results in a platform return type, caller has to explicitly type as non-null
val id: String = requireArguments().getString("user_id", "")
if (id == "") { ... } // ... and check to avoid accidentally using the default value

requireKTX provides methods such as requireString so that you can demand that a value be there, or otherwise get an exception:

val id: String = requireArguments().requireString("user_id")

These methods in the library will throw meaningful exceptions based on the error that occurred - see the method docs for details.

To make the nullable case more obvious and explicit, requireKTX also includes getOrNull style methods for everything that it covers with require style methods. These match the conventions of the Kotlin Standard Library, and can make it clearer that null is returned if a value for a key couldn't be fetched.

val userId: String? = requireArguments().getStringOrNull("user_id")

Dependencies

requireKTX is available from MavenCentral.

repositories {
    mavenCentral()
}

It's available in several artifacts which you can import depending on which types you want to get extensions for - see the module descriptions below for more info:

dependencies {
    implementation "co.zsmb:requirektx-bundle:1.1.0"
    implementation "co.zsmb:requirektx-intent:1.1.0"
    implementation "co.zsmb:requirektx-navigation:1.1.0"
    implementation "co.zsmb:requirektx-work:1.1.0"
}

Available modules and extensions

Bundle

Given a Bundle, you can require the following types of values:

bundle.requireBoolean()
bundle.requireInt()
bundle.requireLong()
bundle.requireString()
bundle.requireParcelable()
bundle.requireSerializable()

Intent

Given a Intent, you can require its extras Bundle (and then require values from it as seen above):

val extras: Bundle = intent.requireExtras()

Or you can require specific extras directly for various types of values:

// Primitives (examples)
intent.requireBooleanExtra()
intent.requireByteExtra()
intent.requireCharExtra()
intent.requireDoubleExtra()
intent.requireFloatExtra()

// Reference types
intent.requireStringExtra()
intent.requireBundleExtra()
intent.requireCharSequenceExtra()
intent.requireParcelableExtra()
intent.requireSerializableExtra()

// Arrays (examples)
intent.requireBooleanArrayExtra()
intent.requireByteArrayExtra()
intent.requireCharArrayExtra()
intent.requireDoubleArrayExtra()
intent.requireFloatArrayExtra()

... and more!

NavBackStackEntry

The navigation module provides an extension to require the arguments of a NavBackStackEntry, same as you could do for a Fragment:

val args: Bundle = navBackStackEntry.requireArguments()

WorkManager Data

Given a WorkManager Data object (such as inputData inside a worker), you can require the following types of values:

class SomeWorker : Worker() {
    override fun doWork(): Result {
        // Values
        inputData.requireBoolean()
        inputData.requireByte()
        inputData.requireDouble()
        inputData.requireFloat()
        inputData.requireInt()
        inputData.requireLong()
        inputData.requireString()

        // Arrays
        inputData.requireBooleanArray()
        inputData.requireByteArray()
        inputData.requireDoubleArray()
        inputData.requireFloatArray()
        inputData.requireIntArray()
        inputData.requireLongArray()
        inputData.requireStringArray()

        // ...
    }
}

License

Copyright 2021 Márton Braun

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
It is far easier to design a class to be thread-safe than to retrofit it for thread safety later
It is far easier to design a class to be thread-safe than to retrofit it for thread safety later

"It is far easier to design a class to be thread-safe than to retrofit it for thread safety later." (Brian Goetz - Java concurrency: Publisher: Addiso

A kotlin library of extension functions that add smalltalk style methods to objects.

KtTalk A kotlin library of extension functions that add smalltalk style methods to objects. Motivation Smalltalk is a pure OO language in which everyt

Use Flink's Stateful Functions as a control-plane technology for operating a streaming-platform
Use Flink's Stateful Functions as a control-plane technology for operating a streaming-platform

statefun-ops Use 🌰 Flink Stateful Functions as a control-plane technology for operating a streaming-platform based on Apache Kafka. Walkthrough Ensur

Notemarks-app - An application that functions to take notes, there is a priority label to categorize which priority is more important ListUtil.kt ListUtils - Advance list functions from kotlin standard library
ListUtil.kt ListUtils - Advance list functions from kotlin standard library

ListUtils - Advance list functions from kotlin standard library A set of utility functions to work with lists in a robust way. It is based on a patter

An android lib that provides most commonly used utility function

Awesome-Utility An android lib that provides most commonly used utility function. It can help Android developers with supporting common utility functi

 Utility for developers and QAs what helps minimize time wasting on writing the same data for testing over and over again. Made by Stfalcon
Utility for developers and QAs what helps minimize time wasting on writing the same data for testing over and over again. Made by Stfalcon

Stfalcon Fixturer A Utility for developers and QAs which helps minimize time wasting on writing the same data for testing over and over again. You can

Kotlin utility mod for Minecraft
Kotlin utility mod for Minecraft

Lambda is a free, open-source, Minecraft 1.12.2 utility mod providing a visionary system for plugins that allow customizing the clients features thank

Disk Usage/Free Utility - a better 'df' alternative
Disk Usage/Free Utility - a better 'df' alternative

duf Disk Usage/Free Utility (Linux, BSD, macOS & Windows) Features User-friendly, colorful output Adjusts to your terminal's theme & width Sort the re

Releases(1.2.0)
Owner
Márton Braun
Android Developer Advocate @GetStream, GDE for Kotlin & Android, Android Tech Editor @raywenderlich, Instructor @bmeaut.
Márton Braun
A library provides some useful kotlin extension functions

ktext ?? A library provides some useful kotlin extension functions. Including in your project Gradle Add below codes to your root build.gradle file (n

热心市民苏苏仔 76 Oct 26, 2022
Android Library to make SharedPreferences usage easier.

KotlinPreferences Kotlin Android Library, that makes preference usage simple and fun. KotlinPreferences now have a brother. With KotlinPreferences, yo

Marcin Moskała 50 Nov 6, 2022
Kstr is a set of helpful methods library for Kotlin intended for make the developer life easier.

Kstr is a set of helpful methods library for Kotlin intended for make the developer life easier. Kstr uses the powerful feature of extension func

Rafael Acioly 0 Nov 3, 2021
Elixir is a library designed to make minecraft login easier.

Elixir Elixir is a library designed to make minecraft login easier. Usage We have a maven repo for this project. repositories { maven { url = "htt

null 4 Aug 11, 2022
A small DSL to make building a conversation in Bukkit easy.

Konversation Konversation provides a simple builder to construct chains of prompts to be used in the conversation API present in Bukkit. Bukkit only p

Tim Hagemann 2 Dec 4, 2022
Android utilities for easier and faster Kotlin programming.

Android utilities for easier and faster Kotlin programming. Download Gradle compile 'com.costular:kotlin-utils:0.1' How to use It depends on utilities

Diego Francisco Concepción 51 Oct 3, 2022
Stateful is a Kotlin library which makes Android application development faster and easier.

Stateful Stateful is a Kotlin library which makes Android application development faster and easier. It helps you delete all the boilerplate code for

PicsArt 67 Oct 3, 2022
A fragment binding library - the easier, efficient way.

Byda allprojects { repositories { ... maven { url 'https://jitpack.io' } } } dependencies { implementation 'com.github.Codzure:B

null 3 May 27, 2021
A set of extension properties on Int, Long, Double, and Duration, that makes it easier to work with Kotlin Duration

Kotlin Duration Extensions Gradle Groovy repositories { mavenCentral() } implementation 'com.eygraber:kotlin-duration-extensions:1.0.1' Kotlin rep

Eliezer Graber 8 Nov 8, 2022
A React Native library making file access easier for developers as first class citizens, without the tears

React Native File Gateway A React Native library making file access easier for developers as first class citizens, without the tears. ⚠️ NOTE: This li

Jimmy Wei 4 Sep 11, 2021