Friday 9 February 2018

Kotlin: Declare extensions as members of other class


You can define extension to class ‘A’ in other class ‘B’. Inside the extension function, you can use the methods of class ‘A’ directly.

class A {
         fun sayHello() {
                 println("Hello")
         }

         fun sayWelcome() {
                 println("Welcome")
         }
}

Let me define other class ‘B’ that add extension function to B.

class B {
         fun A.welcomeUser() {
                 sayHello()
                 sayWelcome()
         }
}

Find the below working application.

HelloWorld.kt
package com.sample.test

class A {
 fun sayHello() {
  println("Hello")
 }

 fun sayWelcome() {
  println("Welcome")
 }
}

class B {
 fun A.welcomeUser() {
  sayHello()
  sayWelcome()
 }

 fun welcomeUser() {
  var obj = A()
  obj.welcomeUser()
 }
}

fun main(args: Array<String>) {
 var obj = B()

 obj.welcomeUser()

}

Output
Hello
Welcome





Previous                                                 Next                                                 Home

No comments:

Post a Comment