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

后端 未结 2 670
暖寄归人
暖寄归人 2021-01-05 01:55

For example, FastUtil\'s IntArrayList has a push method that accepts both int (primitive) and Integer (boxed), but Kotlin

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-05 02:32

    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)
    

提交回复
热议问题