Think of the number of times you had to write util classes in Java to achieve some functionality in your code. If not that, then think of the number of times you had to use patterns like the Decorator pattern to achieve some functionality. All these patterns work but had a certain inelegance to them, which is why Kotlin came up with the simple, yet powerful Extension Functions.
These functions allow you to extend a class with new functionality without having to inherit from the class itself. Once you write an extension function on a particular class, you can call that function on any type of that class as if it were declared in the original one.
Writing an extension function
You declare the extension function the same way you write a normal function in kotlin. However, you need to prefix the name of that method with the receiver type, that is, the type you wish to extend. To easily understand this, let use consider the following code that loads images with Glide.
fun loadImagesWithGlide(imageView: ImageView, url: String) {
Glide.with(imageView)
.load(url)
.centerCrop()
.error(R.drawable.ic_broken_image)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.movie_loading_animation)
.into(imageView)
}
This is just standard code and it will work perfectly on Android. However, let us see how we can make it more interesting with extension functions.
Consider the following code that does the same thing.
fun ImageView.loadImagesWithGlideExt(url: String) {
Glide.with(this)
.load(url)
.centerCrop()
.error(R.drawable.ic_broken_image)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.movie_loading_animation)
.into(this)
}
As you can see above, the number of parameters has now reduced. Notice that the this keyword has now been added. That keyword stands for your receiver, which is ImageView in this case. Once you do this, you can use this on any ImageView you have as if the function loadImagesWithGlideExt(url: String) was declared in the original class as follows.
myImageView.loadImagesWithGlideExt("Your Image URL here")
And just like that, you have greatly cleaned up your kotlin code and seen the power these functions have. The next time you have to log something or show a view, why not use an extension function simply and speed up the process?
Note
You do not actually add any functionality to the original code. You simply make new functions that you can use the dot notation on members of that particular type.
Final words
As you have seen, extension functions are not only simple but extremely powerful as well. The potential is limitless and so you should use them extensively to simplify your code. In the process, you also write cleaner, concise, and easily readable code.
Until next time!