Q:

Kotlin program | Extension function features

belongs to collection: Kotlin Function Programs

0

Extension function

  • Kotlin provides the ability to add more functionality to the existing class without inheriting them.
  • This is done via a special declaration called "Extension'.
  • When a function added into an existing User-defined or Library class called 'Extension Function'.
  • It can also define extensions of functions and properties for companion objects.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program for extension function features in Kotlin

package com.includehelp

// Declare class
class MyClass1{
    // Member function
    fun sayHello(){
        println("Say Hello")
    }
}

// Declare class
class MyClass2{
    // create companion object to call method with class name
    companion object{
        // companion object function
        fun display(){
            println("Display from Companion Object !!")
        }
    }
}

// define Extension function for MyClass1
fun MyClass1.greetExtn(){
    println("Greetings from Extension Function !!")
}

// define extension for Int Class
fun Int.isOdd(){
    if(this%2==0){
        println("Number is ODD")
    }
}

// Define Extension function for MyClass2 Companion object
fun MyClass2.Companion.printData(){
    println("Extension function for Companion object !!")
}

// Main Function, Entry point of Program
fun main(){
    // Create Instance
    val myClass1 = MyClass1()

    // Called member function of class
    myClass1.sayHello()

    // Called extension function
    myClass1.greetExtn()

    // Called Int Class extension Function
    24.isOdd()

    // Called companion object member function
    MyClass2.display()

    // Called companion object extension function
    MyClass2.printData()
}

Output:

Say Hello
Greetings from Extension Function !!
Number is ODD
Display from Companion Object !!
Extension function for Companion object !!

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< Kotlin program | Default and named argument of a f...