Use Cases

Explore the versatility of extension functions for simplifying complex operations, enhancing API interfaces, and streamlining data transformations.

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.

Press + to interact
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 ...