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
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 2 3 4 5 |
fun ClassName.functionName(parameters): ReturnType { // function body } |
1. Example of Extension function in Kotlin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Extension function to remove empty space from string fun String.removeWhitespace(): String = replace("\\s".toRegex(), "") // Usage fun main() { val testString = "This is a sample Text String!!" println(testString.removeWhitespace()) } // Output ThisisasampleTextString!! |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Extension function to reverse a string fun String.reverseText(): String { return this.reversed() + "--Done" } // Usage fun main() { val testString = "Hello, Kotlin!" println("Test String: $testString") println("Reversed: ${testString.reverseText()}") } // Output // Test String: Hello, Kotlin! // Reversed: !niltoK ,olleH--Done |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Extension function to Round to number to given digits fun Double.roundTo(decimals: Int): Double { val factor = Math.pow(10.0, decimals.toDouble()) return Math.round(this * factor) / factor } // Usage fun main() { val pi = 3.14159 println(pi.roundTo(2)) } // Output // 3.14 |
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.