Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One solution to remove ambiguity in overload resolution when calling a generic overloaded Java class from Kotlin is to use the @JvmName annotation in Kotlin. This annotation allows the Kotlin compiler to generate a specific method name that is different from the default method name generated by Kotlin.

For example, if there are two overloaded methods of a Java class with the same name but different types of generic parameters, Kotlin’s compiler will not be able to distinguish which method to call. However, by using the @JvmName annotation, Kotlin can generate a different name for each method, allowing the compiler to differentiate between them.

Here is an example:

Java class:

public class Example<T> {
  public void doSomething(T value) {
    System.out.println("doSomething with " + value.getClass().getSimpleName());
  }

  public void doSomething(List<T> values) {
    System.out.println("doSomething with list of " + values.get(0).getClass().getSimpleName() + " size: " + values.size());
  }
}

Kotlin code:

@JvmName("doSomethingWithValue")
fun <T> Example<T>.doSomething(value: T) = this.doSomething(value)

@JvmName("doSomethingWithList")
fun <T> Example<T>.doSomething(values: List<T>) = this.doSomething(values)

By using the @JvmName annotation, Kotlin generates specific method names for each overloaded method, which allows the compiler to differentiate between them.