Kotlin Introduction
- Kotlin Hello World
- Kotlin Data Types
- Kotlin Operators
- Kotlin Type Conversion
- Kotlin Expression & Statement
- Kotlin Comments
- Kotlin Input/Output
Kotlin Flow Control
- Kotlin if expression
- Kotlin when Expression
- Kotlin while Loop
- Kotlin for Loop
- Kotlin break
- Kotlin continue
Kotlin Functions
Kotlin OOP
- Kotlin Class and Objects
- Kotlin Constructors
- Kotlin Getters and Setters
- Kotlin Inheritance
- Kotlin Visibility Modifiers
- Kotlin Abstract Class
- Kotlin Interfaces
- Kotlin Nested and Inner Classes
- Kotlin Data Class
- Kotlin Sealed Class
- Kotlin Object
- Kotlin Companion Objects
- Kotlin Extension Function
- Kotlin Operator Overloading
In this article, you will learn to extend a class with new functionality using extension functions.
Suppose, you need to extend a class with new functionality. In most programming languages, you either derive a new class or use some kind of design pattern to do this.
However, in Koltin, you can also use extension function to extend a class with new functionality. Basically, an extension function is a member function of a class that is defined outside the class.
For example, you need to use a method to the String class that returns a new string with first and last character removed; this method is not already available in String
class. You can use extension function to accomplish this task.
Example: Remove First and Last Character of String
fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1)
fun main(args: Array<String>) {
val myString= "Hello Everyone"
val result = myString.removeFirstLastChar()
println("First character is: $result")
}
When you run the program, the output will be:
First character is: ello Everyon
Here, an extension function removeFirstLastChar()
is added to the String
class.
The class name is the receiver type (String
class in our example). The this
keyword inside the extension function refers the receiver object.
If you need to integrate Kotlin on the top of Java project, you do not need to modify the whole code to Koltin. Just use extension functions to add functionalities.