Updated April 5, 2023
Introduction to Kotlin extension function
The kotlin extension function is one of the mechanisms that can be provided to extend the class with new functionality without inheriting from the other classes like parent and child classes other design patterns are able to call the classes and their attributes so that their methods make it available for calling the usual ways and if the methods of the original class it may be of any type like access modifiers final will be called its method and the instance of the destination class and its parameters with the extension properties that may create a new property of the existing classes.
Syntax
In kotlin language has many default keywords, variables, and other functions for implementing the application. Among that extension is one of the functions for extending one classes from another. We can use an interface also for to extend the class and other parent classes. And also we can extend the data type like Int, String, etc.
fun main()
{
fun datatype.method():datatype{
---some logics depends on the requirement---
}
}
The above code is the basic syntax for utilizing the extension function on the kotlin language. Like that we can use classes and interfaces etc.
How does the extension function work in Kotlin?
The extension function is like the mechanism for extending the classes, data types like Int, Float, String, etc. Mainly Extensions are mainly visible from the classes like java reflection along with the static methods in its classes and also it will invoke the extension function for the certain source and target classes. We can call and invoked the static along with the final java class and method with their instance of the target or destination classes method parameters. When compared to the member function it is easier to find the extension functions and they are guaranteed to be the class and its member of any type like superclasses and interfaces. The extension functions for the data classes should use only the data carriers and they can’t carry the states by themselves on the data class. It is also primarily called the other code change and may want to change the complex expression around some library objects into easier and more readable expressions. The extension functions when don’t have the access to that class it belongs to the libraries which used by the file and if suppose it’s not to be created. If the class does not use the method and it does not have to extend it so that time also extension function will be used.
Examples of Kotlin extension function
Below are the different examples of Kotlin extension functions:
Example #1
Code:
fun MutableList<Int>.swap(inp1: Int, inp2: Int):MutableList<Int> {
val res = this[inp1]
this[inp1] = this[inp2]
this[inp2] = res
return this
}
fun main(args: Array<String>) {
println("Welcome To My Domain its the first example that related to the kotlin extension function")
val ls = mutableListOf(15,30,45,60)
println("Your inputs before swapped :$ls")
val out = ls.swap(0, 2)
println("Your inputs after swapping the ls :$out")
val num1 = listOf(25,50, 75, 100)
val res1 = num1.minByOrNull { it % 3 }
println(res1)
val str = listOf("Janurary is the first month", "February is the second month", "March is the third month", "April is the fourth month","May is the fifth month","June is the sixth month","July is the seventh month","August is the eigth month","September is the ninth month","October is the tenth month","November is the eleventh month","December is the twelth month")
val strres = str.maxWithOrNull(compareBy { it.length })
println(strres)
val num2 = listOf(35, 70, 105, 140)
val res2 = num2.reduce { res2, x -> res2 + x }
println(res2)
val out2 = num2.fold(0) { res2, x -> res2 + x * 4 }
println(out2)
val num3 = listOf(45, 90, 135, 180, 205)
val res3 = num3.foldIndexed(0) { p, y, z -> if (p % 2 == 0) y + z else y }
println(res3)
val out3 = num3.foldRightIndexed(0) { p, z, y -> if (p % 2 == 0) y + z else y }
println(out3)
}
Sample Output:
In the first example, we used mutablelist class and its feature to extend the functionality of the swapping numbers.
Example #2
Code:
class Second {
companion object {
fun demo(): String {
return "Thank you for creating and utilising the extension function on this method"
}
}
}
class Employee {
var salary:Int = 10000
var name:String="Sivaraman"
var empid: Int=41
fun empdetails(){
println("The Employee details are: ${this.name},${this.empid},${this.salary}")
}
companion object New{
var x: Int = 3
fun dem(){
println("Your input value is: $x")
x++
}
}
}
fun Second.Companion.demo1() {
println("Welcome To My Domain its the second example that related to the kotlin extension function")
}
fun main(args: Array<String>) {
Second.demo1()
val num3 = listOf(2, 4, 6, 8, 10, 12, 14,16,18,20)
val inp1 = num3.runningReduce { u, v -> u + v }
val inp2 = num3.runningFold(10) { u, v -> u + v }
val res = { w: Int, z: Int -> "The Net Result is: = ${w + 1}: $z" }
println(inp1.mapIndexed(res).joinToString("\n", "Thank you users for spenting the time with us:\n"))
println(inp2.mapIndexed(res).joinToString("\n","Please keep and continue your valuable time with us"))
}
Sample Output:
In the second example we used class and companion objects we can extend the companion object method like demo1() and it’s called in the main method.
Example #3
Code:
fun String.removeFirstLastChar(): String = this.substring(3, this.length - 1)
fun main(args: Array<String>) {
println("Welcome To My Domain its the third example that related to the kotlin extension function")
val str= "The home contains tv,fridge,bureau, cuphoard, bed, washing machine, PC, Webcam,oven,grinder,mixie and other househod things which are valuable for maintaing house"
val res = str.removeFirstLastChar()
println("Have a Nice day users please keep on spenting your valuable time with us: $res")
}
Sample Output:
In the final example, we used substring() string method in the extension function to trim the characters and print the console screen.
Conclusion
In a programming language, we used extend keywords to extend the parent and child classes even interfaces will be implemented and extend with the class. Here kotlin extension it extend the functions and classes, companion objects, and other default methods and customized keywords extend with their properties and features of the application.
Recommended Articles
This is a guide to the Kotlin extension function. Here we discuss the introduction, syntax, and working of extension functions in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –