InterviewSolution
| 1. |
What do you understand about function extension in the context of Kotlin? Explain. |
|
Answer» 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: // KOTLINclass Sample { var STR : String = "null" fun printStr() { print(str) } }fun main(args: Array<String>) { var a = Sample() a.str = "Interview" var B = Sample() b.str = "Bit" var c = Sample() c.str = a.add(b) c.printStr()}// function extensionfun Sample.add(a : Sample):String{ var temp = Sample() temp.str = this.str + " " +a.str return temp.str}Output:- Interview BitExplanation:- We don't have a method named "addStr" inside the "Sample" class in the preceding example, but we are implementing the same method outside of the class. This is all because of function extension. |
|