Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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()

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.


This comment has been minimized.

Copy link

@dkandalov dkandalov commented Jul 30, 2017

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