Today, we are announcing the preview of Android KTX - a set of extensions designed to make writing Kotlin code for Android more concise, idiomatic, and pleasant. Android KTX provides a nice API layer on top of both Android framework and Support Library to make writing your Kotlin code more natural.

The portion of Android KTX that covers the Android framework is now available in our GitHub repo. We invite you to try it out to give us your feedback and contributions. The other parts of Android KTX that cover the Android Support Library will be available in upcoming Support Library releases.

Let's take a look at some examples of how Android KTX can help you write more natural and concise Kotlin code.

Code Samples Using Android KTX

String to Uri

Let's start with this simple example. Normally, you'd call Uri.parse(uriString). Android KTX adds an extension function to the String class that allows you to convert strings to URIs more naturally.

Kotlin

Kotlin with Android KTX

val uri = Uri.parse(myUriString)

val uri = myUriString.toUri()

Edit SharedPreferences

Editing SharedPreferences is a very common use case. The code using Android KTX is slightly shorter and more natural to read and write.

Kotlin

Kotlin with Android KTX

sharedPreferences.edit()
.putBoolean(key, value)
.apply()

sharedPreferences.edit {
putBoolean(key, value)
}

Translating path difference

In the code below, we translate the difference between two paths by 100px.

Beware that the APIs are likely to change during the preview period. If you decide to use it in your projects, you should expect breaking changes before we reach the stable version.

androidx: Hello World!

You may notice that Android KTX uses package names that begin with androidx. This is a new package name prefix that we will be using in future versions of Android Support Library. We hope the division between android.* and androidx.* makes it more obvious which APIs are bundled with the platform, and which are static libraries for app developers that work across different versions of Android.

What's Next?

Today's preview launch is only the beginning. Over the next few months, we will iterate on the API as we incorporate your feedback and contributions. When the API has stabilized and we can commit to API compatibility, we plan to release Android KTX as part of the Android Support Library.

We look forward to building Android KTX together with you. Happy Kotlin-ing!