Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Extension Function on a Java Class

Tags:

kotlin

Is it possible to add a static extension function similar to a adding an extension function to a companion object. I tried

public fun ByteBuffer.Companion.invoke(capacity: Int): ByteBuffer

but it caused Unresolved referenced: Companion. I would only assume this is because Companion is not defined in the java code.

like image 680
sublixt Avatar asked Apr 27 '15 04:04

sublixt


1 Answers

Update (November 2021): JetBrains planning to prototype a solution for static extension functions for any third-party classes, including Java ones!

It will be based on introducing the new concept of a namespace – a kind of ephemeral object without an instance that every class automatically possesses, so that an extension to a class’s namespace can be introduced to any third-party class, and namespace members are naturally compiled down to static members on the JVM. This keeps static helpers grouped together in the source, but removes all the object overhead.

This is also supposed to significantly improve Kotlin's interoperability with Java's static methods and will enable extensions on any Java types, so it should help with Kotlin/JVM adoption!

Short answer: It is not possible at this moment. But could be supported in the future.

You are right, Java classes don't have companion objects. You can add extensions only to classes (will show on instances of the class) or to declared companion objects (will look like static on the class):

class A { companion object }
class B { companion object Test }

fun A.Companion.foo() { println("Test A.foo") }
fun B.Test.foo() { println("Test B.foo") }

fun main(args: Array<String>) {
    A.foo() // prints «Test A.foo»
    B.foo() // prints «Test B.foo»
}
like image 79
Artyom Krivolapov Avatar answered Oct 13 '22 11:10

Artyom Krivolapov