Using Core KTX

Core KTX includes packages built around a variety of core Android framework libraries and APIs, including the following:

One of the best examples of using Android KTX to simplify platform APIs is in the use of SharedPreferences. With the functionality of Kotlin available to us, we can use a very fluent syntax for editing SharedPreferences that removes the need to explicitly call commit() or apply():

val preferences = getPreferences(Context.MODE_PRIVATE)
preferences.edit {
putBoolean("key", false)
putString("key2", "value")
}

Another example of useful functionality provided by Android KTX is the View.onPreDraw() extension function:

button.doOnPreDraw {
// Perform an action when view is about to be drawn
}

This allows us to define a lambda containing logic that will be run when View is about to be drawn without having to create a new listener or having to unregister that listener.