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 BookSimpan untuk Revisi
Simpan untuk Revisi
Bookmark item ini, tandai sebagai sulit, atau masukkan ke dalam set revisi.
Masuk untuk menyimpan bookmark, pertanyaan sulit, dan set revisi.