androidkotlinsdkkotlin-java-interop

use static Java methods as static (or singleton) properties in Kotlin


My SDK exposes a Java interface that has only static methods, e.g.

public interface MyDevice { 
  public static void setLocation(Location location) {…}
  public static Location getLocation() {…}
}

In Java app that uses the SDK, my customers can use these as if it were a singleton, e.g.

Location currentLocation = MyDevice.getLocation();

When this SDK is integrated into a Kotlin app, it would be natural to express the same as a property:

val currentLocation = MyDevice.location

The problem is, this built-in interop works for non-static methods only.

I can create a singleton in Kotlin and have it handle the translation:

object myDevice {
    var location: Location
    get() = MyDevice.getLocation()
    set(location) = MyDevice.setLocation(location)
}

But won't this single Kotlin file in an otherwise Java-only SDK negatively affect the customers who don't use Kotlin? Can the same be expressed in Java?

Or maybe I should simply convert MyDevice.java to Kotlin? What will be negative effects of such step for the customers who are still on Java?


Solution

  • Having read the answers of the experts, having studied the links they provided, and having decompiled the Kotlin code of the wrapper class and analyzed a demo app (pure Java) which used the Kotlin-wrapped library, I decided to change the Java API.

    Now I have a class with a public static object:

    public class MyDevice { 
      public static MyDevice myDevice;
      public void setLocation(Location location) {…}
      public Location getLocation() {…}
    }
    

    now the Java consumers will use

    import static com.example.sdk.MyDevice.myDevice;
    

    Kotlin consumers don't need that static:

    import com.example.sdk.MyDevice.myDevice
    

    So, I don't need a separate Kotlin flavor of my library!