English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Extension Functions

Kotlin OOP (Object-Oriented Programming)

In this article, you will learn how to use extension functions to extend classes with new features.Suppose you need to extend a class with new features. In most programming languages, you eitherDerive a new class,

Either use some design pattern to perform this operation.

However, in Kotlin, you can also use extension functions to extend classes with new features. Essentially, extension functions are member functions of a class defined outside the class.For example, you may need toString class

Example: Remove the first and last characters of a string. This method does not exist in the String class. You can use an extension function to complete this task.

fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1)
fun main(args: Array<String>) {
    val myString = "Hello Everyone"
    val result = myString.removeFirstLastChar()
    println("Output result: $result")
}

When the program is run, the output is:

Output result: ello Everyon

Here, the extension function removeFirstLastChar () is added to the String class.

The class name is the receiver type (in our example, the String class). The this keyword in the extension function refers to the receiver object.

If you need to integrate Kotlin into the top of a Java project, you do not need to modify the entire code to Kotlin. You can simply add functionality using extension functions.