15

For example I have Java class (from external library):

class A {} // This is Java class

I want to add extension functions written on Kotlin and call it as:

A.foo() // This is call of extension function `foo` from Kotlin code

As I understand, right now it is impossible to do in Kotlin because it support "static" extension functions for KClass-es with companion object only. Right?

Seems like nothing to prevent to implement such functionality in Kotlin later. Right?

UPDATE 2019-06-12: This question doesn't answer to my question because my question about compatibility of Kotlin extension functions with Java classes.

Maxim
  • 9,701
  • 5
  • 60
  • 108
  • Why do you need this? You could just define a regular function in a package to get the same effect, except you don't have to use a class name with dot syntax to call it. If you're expecting to use reflection to find the static method in some class, that's a different story... – Doug Stevenson Mar 15 '16 at 22:47
  • I just want to use `A.foo()` syntax instead of `foo(A)` because Kotlin promote such syntax for extending functionality of classes (see first paragraph [here](https://kotlinlang.org/docs/reference/extensions.html#extensions)). – Maxim Mar 15 '16 at 23:10
  • 2
    Right, extension functions and properties are for *instances* of classes. You don't have an instance here, just a function call. – Doug Stevenson Mar 15 '16 at 23:28
  • But, if you want to replace `A.foo()` with `foo(A)`, it means that you will need a instance of `A` in the case of `foo(A)`, right? If so, why not use the extension function for instances and do `a.foo()`? – marcospereira Mar 16 '16 at 02:00
  • I'm saying you don't define a function inside class A at all. You just define it within some package, import it in the code where you want to use it, then call it without any enclosing class reference. Static methods don't require an instance of anything at all outside of its declared parameter, and that's the same for kotlin functions defined in a package. – Doug Stevenson Mar 16 '16 at 07:55
  • Possible duplicate of [Static extension methods in Kotlin](https://stackoverflow.com/questions/28210188/static-extension-methods-in-kotlin) – kyay10 Jun 12 '19 at 04:09

1 Answers1

28

You're right. In Kotlin 1.0, you can define extension functions on a companion object of a Kotlin class, and such functions can be called using the A.foo() syntax. Support for defining static extension functions on Java classes is a possible feature for future versions of Kotlin, but it's not on the roadmap of Kotlin 1.1 at this time.

yole
  • 92,896
  • 20
  • 260
  • 197