Skip to content

Instantly share code, notes, and snippets.

@npryce
Last active July 30, 2017 13:28
Show Gist options
  • Save npryce/b3710efcecd031b4321e6d4e7a58b8d0 to your computer and use it in GitHub Desktop.
Save npryce/b3710efcecd031b4321e6d4e7a58b8d0 to your computer and use it in GitHub Desktop.
Kotlin/Java interop method overloading pitfall

Given a Java library that defines overloaded methods for primitive and boxed types:

class X {
    public void m(int value) { ... }
    public void m(Integer value) { ... }
    ...
}

Kotlin cannot resolve a call to the overloaded method, because it does not distinguish between primitive and heap allocated types.

This code:

val x = X()
x.m(10)

Results in a compile-time error:

... TBD ...

A workaround we've found is to define a Java class with unambiguous static methods that forward to one of the overloaded methods. E.g.

class XDisambiguation {
    public static void mInt(X x, int i) { x.put(i); }
    public static void mInteger(X x, Integer i) { x.put(i); }
}

Then in Kotlin we can call either XDisambiguation.mInt(x, i) or XDisambiguation.mInteger(x, i) as required.

We'd usually hide the static calls with convenient extension methods on X.

@dkandalov
Copy link

Btw, there is no compilation error at least since kotlin 1.1.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment