Kotlin program | Extension function features

Kotlin | Extension function features: Here, we are implementing a Kotlin program to demonstrate the example of Extension function features.
Submitted by IncludeHelp, on May 31, 2020

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.

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 !!


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.