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) {
var obj = B()
obj.welcomeUser()
}
Output
Hello
Welcome
Previous Next Home
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here