What do you understand about function extension in the context of Kotlin? Explain.
In Kotlin, we can add or delete method functionality using extensions, even without inheriting or altering them. Extensions are statistically resolved. It provides a callable function that may be invoked with a dot operation, rather than altering the existing class.
Function Extension - Kotlin allows users to specify a method outside of the main class via function extension. We\'ll see how the extension is implemented at the functional level in the following example:
// KOTLIN
class Sample {
var str : String = "null"
fun printStr() {
print(str)
}
}
fun main(args: Array) {
var a = Sample()
a.str = "Without"
var b = Sample()
b.str = "Book"
var c = Sample()
c.str = a.add(b)
c.printStr()
}
// function extension
fun Sample.add(a : Sample):String{
var temp = Sample()
temp.str = this.str + \" \" +a.str return temp.str
}Output:-
Without BookGuardar para repaso
Guardar para repaso
Guarda este elemento en marcadores, marcalo como dificil o agregalo a un conjunto de repaso.
Inicia sesion para guardar marcadores, preguntas dificiles y conjuntos de repaso.