If you’re developing an Android application with Kotlin, then I have a good news for you. Recently Google released an Android ktx library, which is a set of Kotlin Extension function. Android ktx is a part of Jetpack family. The purpose of Android ktx is to write less code and more concise. Android ktx brings us lots of extension functions, named parameters, lambdas, and parameter with the default value. It does not add any new features to existing Android Api’s.

I read all the documentation on android-ktx and thought to write some notes on it. It’s not just reading on Android developer documentation. We’re going to see the extension functions with example and explore most of them.

Note: Android ktx is currently in preview mode but it is open for the developer to give it a try and give feedback to contributors. It may be offering more extension functions when it is released.

To get started with Android ktx add the google repository in build,gradle file.

repositories { 

Android ktx dependency in split into the modular approach. By modular means, you don’t have to add the core dependency, if you do not want to use all of the extension’s functions. Here is the list of dependency of Android ktx.

implementation 'androidx.core:core-ktx:$currentVersion'
implementation 'androidx.fragment:fragment-ktx:$currentVersion'
implementation 'androidx.palette:palette-ktx:$currentVersion'
implementation 'androidx.sqlite:sqlite-ktx:$currentVersion'
implementation 'androidx.collection:collection-ktx:$currentVersion'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:$currentVersion'
implementation 'androidx.lifecycle:lifecycle-reactivestreams-ktx:$currentVersion'
implementation 'android.arch.work:work-runtime-ktx:$currentVersion'

After syncing the project you’re good to go to use Android ktx. Now let’s start with the first modular dependency.

1. Fragment-ktx:

Fragment ktx dependency right now supports only one extension function. The only extension function is about triggering the fragment transaction. Without ktx performing a fragment transaction, the transaction requires starting a transaction triggering an action like replacing or adding a fragment and then the signing on one of the four commit methods. Now let’s see how we can remove the boilerplate code with fragment ktx extension.

supportFragmentManager.transaction(now = false, allowStateLoss = false) {
      replace(R.id.frag_container, myFrament,FRAGMENT_TAG)

Fragment ktx as the transaction extension function to the FragmentManager class removing all the begin transaction boilerplate code. As well as providing the four value for sync and stateloss that you can easily override.


2. Palette-ktx:

Like I said the library is currently in the preview that’s why we only have two extension function for palette ktx. Now let’s take a look at what extension function we have…?

Now you can easily create Palette. Builder with the bitmap.

val paletteBuilder : Palette.Builder = bitmap.buildPalette()

You can easily get Palette. Swatch from Palette class.

val paletteSwatch = pallete[Target.DARK_VIBRANT]

Returns the selected swatch for the given Target from the palette, or if null one could not be found. With palette swatch, you can retrieve RGB color by calling the getRgb method.

3. SQLite-ktx:

SQLite ktx dependency right now supports only one extension function. When implementing database transaction you need a lot of boilerplate code, with the SQLite ktx, you can focus on what matters the operation that you want to make in the database. Let’s see an example of handling transaction with sqlLite ktx.

sqLitedatabase.transaction(exclusive = true){
    // Insert data, delete data, update data

If you setting exclusive to true it called beginTransaction and when setting false it called beginTransactionNonExclusive.

4. Collection-ktx:

If you use the Kotlin top-level function of creating collection then you absolutely love this collection ktx dependency. It supports many extension functions and it also supports top-level function of creating the collection. Let’s see them one by one.

4.1 Collection-ktx Top-level Functions:

With the .collection package of ktx, you can easily create an arrayMapOf with top-level function to create ArrayMap.

val arrayMap = arrayMapOf<String,String>()   // returns an empty new ArrayMap

You can also give a list of Pair where the first component is the key and second component is the value.

map = arrayMapOf(pairs = *arrayOf(
          Pair("Jon", "Doe"),
          Pair("Hilary", "Clinton"))
)    // returns a array map with specified content.

The ArraySet also gives some top-level function to ease the process when working with them.

val arraySet = arraySetOf<Int>()   // returns an empty new ArraySet.

You can also give a vararg to create ArraySet.

val arraySet = arraySetOf(1,2,3)  // return an array set with specified content.
4.2 Collection-ktx Extension Functions:

When working with the LongSparseArray and SparseArrayCompat we can make use of the below extension function. Both of the classes pretty much offers the same functionalities.

val longSparseArray = LongSparseArray<String>()   // create a LongSparseArray of String

//   returns true if the collection contain the key
longSparseArray.contains(key: Long)    

// You can use index operator to store value a specified index
longSparseArray.set(key : Long,value : String)   // value is String, because our sparse array is String type

// create new collcetion by adding or replacing entries from other
longSparseArray.plus(other : LongSparseArray<String>)

// returns true if the collection contains the key
longSparseArray.containsKey(key : Long)

// return true if the collection contains the value
longSparseArray.containsValue(value : String)

// return the value corresponding to the key, or default when no present.
longSparseArray.getOrDefault(key : Long, defaultValue : String)  // return defaultValue if no value found according to the key

// return true when the collection contains one or more than element in the array.

// removes the entry from the array only if it is mapped to value in the specified index.
longSparseArray.remove(key : Long, value: String)

// updates this collection by adding replacing entries from other.
longSparseArray.putAll(other: LongSparseArray<String>)

// performs foreach on every key/value entry.
longSparseArray.forEach(action : (key : Long, value : String) -> Unit)

// Example of foreach function
longSparseArray.forEach{ key,value -> 
     // Use the key and value to perform the operation

// return Iterator over the collection key.
val iterator : LongIterator = longSparseArray.keyIterator()

// return Iterator over the collection values.
val iterator : Iterator<String> = longSparseArray.valueIterator()

That’s it guy’s, I’m going to end this blog here for more further reading about Android ktx see the part 2. In the next part, I’m going to explain about lifecycle ktx, reactive streams ktx and runtime ktx. Finally, in the third part, we’re gonna explore the core ktx.

I hope you guy’s have learned something from this post. If you’ve any queries about this post please do comment below.

Thank you for being here and keep reading.

Next Part


I’m a mobile product devsigner (i.e. I consider myself as both a developer and a designer) and user experience/interface engineer. I’m an expert on the Android platform and have been recognized as it by the community.

Write A Comment