Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Kotlin: Extensions to companion object

In my previous post, I explained how to set extensions to an existing class. In this post, I am going to explain how to set extensions to Companion object.

Syntax
fun Type.Companion.functionName(arguments) = definition

C is capital in ‘Companion’

Ex
         fun TestClass.Companion.sum(a: Int, b: Int): Int {
                 return a + b
         }

Just like the normal companion functions call, you can call extension functions.

TestClass.sum(10, 20)

Find the below working application.

HelloWorld.kt
class TestClass {
companion object {
fun sayHello() {
println("Hello")
}
}
}

fun main(args: Array) {
fun TestClass.Companion.sum(a: Int, b: Int): Int {
return a + b
}

var sumOfNumbers = TestClass.sum(10, 20)

println("Sum of 10 and 20 $sumOfNumbers")
}


Output
Sum of 10 and 20 30




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Kotlin: Extensions to companion object

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×