Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add "static" extension function for Java class?

Tags:

kotlin

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.

like image 313
Maxim Avatar asked Mar 15 '16 22:03

Maxim


People also ask

Can you add extension methods to an existing static class?

No. Extension methods require an instance of an object.

Can we define extension method for static class yes or no?

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.

Can we call static function in Java?

Calling Static Function In Java, we cannot call the static function by using the object. It is invoked by using the class name.

Can classes in Java be static?

Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class in which the nested class is defined is known as the Outer Class. Unlike top-level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes.


1 Answers

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.

like image 75
yole Avatar answered Jan 05 '23 06:01

yole