Master Extension Functions in Kotlin with Easy Examples

The extension function in Kotlin allows us to add new functions to existing inbuilt Kotlin classes without modifying their source code. This feature is useful when we want to perform functionality on an existing inbuilt function. We all know about String classes and their string functions. So, by using extension functions, we can modify string class functions. In today’s tutorial, we learn how to use the extension function in Kotlin.

Master Extension Functions in Kotlin with Easy Examples

Master Extension Functions in Kotlin with Easy Examples

Define extension function in Kotlin:

In Kotlin, to define an extension function, first, we declare the Class name of the function we want to extend, then the function name, its parameters, and its return type.

1. Example of Extension function in Kotlin:

Code explanation:

We have created a String extension function to remove empty white spaces from the string. Now this function acts like a normal string function and can be used directly on String.

Example 2:

Code explanation:

We have created a String reverse extension which makes the pass string reverse and adds a custom Done keyword at the end of the reversed string.

Example 3:

Code explanation:

This extension function is a Double return type function that rounds our given number to the given digits. If we pass 2 then it will show only 2 values after a point.

Conclusion:

The extension function provides us way of adding flexibility to our code. We can override the behavior of an inbuild class function without changing its code. This is very helpful when we want a unique type of result. So keep practicing the extension functions to master them, Happy coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *