Saturday, 10 February 2018

Kotlin: Overriding extensions

In kotlin, you can override extensions. To override extension defined in class ‘B’, from class ‘C’, the extension should be defined with ‘open’ in class ‘B’.

Find the below working application.

Test.kt
package com.sample.test

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

open class B {
 open fun A.sayWelcome() {
  println("Welcome defined in class B")
 }

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

class C : B() {
 override fun A.sayWelcome() {
  println("Welcome defined in class C")
 }
}

fun main(args: Array<String>) {
 var bObj = B()
 var cObj = C()

 bObj.welcomeUser()
 cObj.welcomeUser()
}

Output
Welcome defined in class B
Welcome defined in class C






Previous                                                 Next                                                 Home

No comments:

Post a Comment