Search⌘ K
AI Features

Use Cases

Explore how Kotlin extensions can simplify complex operations like UI updates and streamline API interactions. Understand how to use extension functions to enhance standard interfaces and manage object transformations between app and API models effectively.

Simplifying complex operations

The most important use case for extensions is adding methods and properties to APIs that we don’t control. A good example is displaying a toast or hiding a view on Android. Both these operations are unnecessarily complicated, so we like to define extensions to simplify them.

Kotlin 1.5
fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
fun View.hide() {
this.visibility = View.GONE
}

Enhancing API interfaces

However, there are also cases where we prefer to use extensions instead of members. Consider the Iterable interface, which has only one member ...