Learn Kotlin  - Extension Functions

Learn Kotlin%E2%80%8A Extension functions

Extension Functions

What are extension functions?

As the name implies, the extension functions are the functions that help us to extend the functionality of classes without having to touch their code.

In other words, the extension functions in Kotlin allow us to extend the functionality of a class by adding new functions. The class doesn’t have to belongs to us (could it be a third-party library) and also without requiring us to inherit the class.

Really? without inheriting the class.

Yes! It’s possible in Kotlin.

Let’s stop talking, show me how it is possible.

Taking a very simple example to understand.

fun Int.triple(): Int {
  return this * 3
}

// now we can use like this
var result = 3.triple()

Another example, let’s see how we can use this with Android View.

fun ImageView.loadImage(url: String) {
    Glide.with(context).load(url).into(this)
}

// now we can use like this
imageView.loadImage(url)

This looks great!

There are many places in Android Development, where we can use this cool feature of Kotlin. Let’s use this great feature whenever it is required.