Search code examples
kotlincompanion-object

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 ?


Solution

  • 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.