Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: What can I do when a Java library has an overload of both primitive and boxed type?

For example, FastUtil's IntArrayList has a push method that accepts both int (primitive) and Integer (boxed), but Kotlin sees these both as the same function push(Int), therefore I cannot use the function at all as the function is ambiguous.

What should I do when a Java library has overloads for both the primitive and boxed type?

(p.s. I am aware that I can use the add(int) method. I am in search of what to do if I come across such a problem in the future.)

like image 398
Jire Avatar asked Jun 04 '16 01:06

Jire


2 Answers

Consider these methods in Java:

void f(int x) { }
void f(Integer y) { }

In Kotlin, they are seen as

f(x: Int)
f(x: Int!)

The second method has a parameter of platform type, meaning it might be nullable, corresponding to Integer.

First one can be simply called with Kotlin Int passed:

f(5) // calls f(int x)

To call the second one, you can cast the argument to nullable Int?, thus selecting the overload:

f(5 as Int?) // calls f(Integer y)
like image 123
hotkey Avatar answered Sep 25 '22 15:09

hotkey


Have you tried writing a Java class to serve as an intermediary? That is, write your own java class with the method you want Kotlin to see, then call that method from your Kotlin code.

like image 35
user2297560 Avatar answered Sep 24 '22 15:09

user2297560