0

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(){}
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
iPotato
  • 21
  • 1

3 Answers3

1

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

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()
Ric17101
  • 1,063
  • 10
  • 24
0

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!
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74