Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
Extension functions in Kotlin allow developers to "add" methods to existing classes without modifying their source code. These functions are declared outside the class they're extending, and they can be called in the same manner as regular methods. Here's how you can harness the power of extension functions in Kotlin:
fun ClassName.newFunctionName(parameters): ReturnType { // function body }
Let's consider you want to add a method to the String
class that reverses its content:
fun String.reverse(): String { return this.reversed() }
You can then use this extension function like a regular method:
fun main() { val original = "Hello" println(original.reverse()) // Outputs: "olleH" }
Apart from functions, you can also define extension properties:
val String.isNumeric: Boolean get() = this.all { it.isDigit() }
Now, you can check if a string is numeric:
fun main() { val numberString = "12345" println(numberString.isNumeric) // Outputs: true }
this
Keyword in Extension Functions:Inside an extension function, the this
keyword refers to the receiver object (the instance of the class the function extends). In our example above, this
inside the reverse()
function refers to the String
instance on which the function is invoked.
You can also define extension functions on nullable types. For example, if you want a function that checks if a String?
is either null or blank:
fun String?.isNullOrBlank(): Boolean { return this == null || this.isBlank() }
If extension functions are defined in a different file or package, you must import them to use them in another file. The import will look like this:
import packageName.functionName
Extension functions offer a powerful way to augment existing classes with new functionality without modifying their source code or inheriting from them. This leads to more readable and maintainable code. They're especially useful when working with libraries or APIs where the source code can't be changed directly.
How to define extension functions in Kotlin:
fun
keyword with the type you're extending.fun String.myExtensionFunction(): String { return this.toUpperCase() }
Using extension functions in Kotlin:
val result = "hello".myExtensionFunction()
Extension functions vs regular functions in Kotlin:
// Regular function fun capitalize(str: String): String { return str.capitalize() } // Extension function fun String.myExtensionFunction(): String { return this.toUpperCase() }
Extending existing classes with Kotlin extension functions:
fun Int.isEven(): Boolean { return this % 2 == 0 } val result = 10.isEven()
Extension properties in Kotlin:
val String.customLength: Int get() = this.length val length = "hello".customLength
Chaining extension functions in Kotlin:
fun String.toTitleCase(): String { return this.split(" ").joinToString(" ") { it.capitalize() } } val result = "hello world".myExtensionFunction().toTitleCase()
Scoping and visibility in Kotlin extension functions:
fun String.customFunction(): String { return this.publicMember // Access to public members }
Nullability and extension functions in Kotlin:
fun String?.safeExtensionFunction(): String { return this.orEmpty().toUpperCase() }
Working with receiver objects in extension functions:
this
keyword to reference the receiver object.fun String.appendExclamation(): String { return this + "!" }
Library and framework extension functions in Kotlin:
fun RecyclerView.hideScrollBar() { this.isVerticalScrollBarEnabled = false this.isHorizontalScrollBarEnabled = false }