Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin, how to add extension function to already defined class companion object

i want to add some extension function to an already defined class‘s companion object, like

fun Toast.Companion.showImageToast(str : String) {
}

and also i like to do the same thing on interfaces, e.g

fun Runnable.Companion.mainHandler() {
}

I've consulted the documentation, only to find syntax for define extension function for companion object in a user defined class, not for class that don't have a companion object

can i have any chance to do this in kotlin ?

like image 649
Minami Avatar asked Dec 03 '25 13:12

Minami


1 Answers

In Kotlin 1.0, if a class does not define a companion object, it is not possible to define extension functions for that companion object. It's also not possible to define extension functions for Java classes and interfaces such as Runnable.

like image 170
yole Avatar answered Dec 05 '25 09:12

yole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!