Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin extension function

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:

1. Basic Syntax:

fun ClassName.newFunctionName(parameters): ReturnType {
    // function body
}

2. Examples:

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"
}

3. Extension Properties:

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
}

4. 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.

5. Null Safety with Extension Functions:

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()
}

6. Limitations of Extension Functions:

  • Extension functions cannot access private or protected members of the class they're extending.
  • They're resolved statically, based on the declared type of the variable, not the runtime type.

7. Importing Extension Functions:

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

Conclusion:

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.

  1. How to define extension functions in Kotlin:

    • Use the fun keyword with the type you're extending.
    fun String.myExtensionFunction(): String {
        return this.toUpperCase()
    }
    
  2. Using extension functions in Kotlin:

    • Call extension functions on instances of the extended type.
    val result = "hello".myExtensionFunction()
    
  3. Extension functions vs regular functions in Kotlin:

    • Extension functions provide the ability to extend existing types without modifying their source code.
    // Regular function
    fun capitalize(str: String): String {
        return str.capitalize()
    }
    
    // Extension function
    fun String.myExtensionFunction(): String {
        return this.toUpperCase()
    }
    
  4. Extending existing classes with Kotlin extension functions:

    • Extend classes you don't own.
    fun Int.isEven(): Boolean {
        return this % 2 == 0
    }
    
    val result = 10.isEven()
    
  5. Extension properties in Kotlin:

    • Add properties to existing classes.
    val String.customLength: Int
        get() = this.length
    
    val length = "hello".customLength
    
  6. Chaining extension functions in Kotlin:

    • Chain multiple extension functions.
    fun String.toTitleCase(): String {
        return this.split(" ").joinToString(" ") { it.capitalize() }
    }
    
    val result = "hello world".myExtensionFunction().toTitleCase()
    
  7. Scoping and visibility in Kotlin extension functions:

    • Extension functions have access to public members of the extended type.
    fun String.customFunction(): String {
        return this.publicMember // Access to public members
    }
    
  8. Nullability and extension functions in Kotlin:

    • Handle nullability explicitly.
    fun String?.safeExtensionFunction(): String {
        return this.orEmpty().toUpperCase()
    }
    
  9. Working with receiver objects in extension functions:

    • Use the this keyword to reference the receiver object.
    fun String.appendExclamation(): String {
        return this + "!"
    }
    
  10. Library and framework extension functions in Kotlin:

    • Extend classes from external libraries.
    fun RecyclerView.hideScrollBar() {
        this.isVerticalScrollBarEnabled = false
        this.isHorizontalScrollBarEnabled = false
    }