Kotlin:当Java库同时具有原始类型和盒装类型的重载时,我该怎么办? [英] Kotlin: What can I do when a Java library has an overload of both primitive and boxed type?

查看:44
本文介绍了Kotlin:当Java库同时具有原始类型和盒装类型的重载时,我该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,FastUtil的IntArrayList具有push方法,该方法同时接受int(原始)和Integer(盒装),但是Kotlin认为这两个都是相同的函数push(Int),因此我不能使用完全是因为该函数是模棱两可的.

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.

当Java库同时具有原始类型和盒装类型的重载时,我该怎么办?

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

(ps.我知道我可以使用add(int)方法.我正在寻找如果将来遇到此类问题该怎么办.)

(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.)

推荐答案

在Java中考虑以下方法:

Consider these methods in Java:

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

在科特林,他们被视为

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

第二种方法的参数为

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

第一个可以简单地通过传递的Kotlin Int来调用:

First one can be simply called with Kotlin Int passed:

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

要调用第二个,可以将参数强制转换为可为空的Int?,从而选择重载:

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)

这篇关于Kotlin:当Java库同时具有原始类型和盒装类型的重载时,我该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆