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

假装没事ソ 提交于 2019-11-30 20:18:11

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)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!