Ask Your Question
2

What is the solution to remove ambiguity in overload resolution when calling a generic overloaded Java class from Kotlin?

asked 2022-04-05 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2022-12-10 20:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-05 11:00:00 +0000

Seen: 8 times

Last updated: Dec 10 '22