Given a third party class ThirdClass
, which doesn't have a companion object, how can I define a static extension function for it? Something like this:
fun ThirdClass.Companion.hello(){}
Given a third party class ThirdClass
, which doesn't have a companion object, how can I define a static extension function for it? Something like this:
fun ThirdClass.Companion.hello(){}
Not at the moment, but it's tracked under KT-11968: Adding statically accessible members to an existing Java class via extensions (despite the name, the discussion covers Kotlin classes/interfaces without a companion as well). See particularly the comments starting here.
I think what you need is to declare an object inside the class marked as companion like from this link.
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
Members of the companion object can be called by using simply the class name as the qualifier:
val instance = MyClass.create()
You cannot declare a static function from outside of the class definition, but you can make an extension function that will work on all instances:
fun ThirdClass.hello() = println("Hello from ${this.javaClass.name}!")
fun main() {
ThirdClass().hello()
}
Output:
Hello from ThirdClass!