Nullable arg cast bug

I’ve set an example where the same method works with non-nullable arg, and with nullable arg it doesn’t compile.

Error:(10, 14) java: no suitable method found for round(int,int)
method main.kotlin.Fails.round(java.lang.Double,java.lang.Integer) is not applicable
(argument mismatch; int cannot be converted to java.lang.Double)
method main.kotlin.Fails.round(java.math.BigDecimal,java.lang.Integer) is not applicable
(argument mismatch; int cannot be converted to java.math.BigDecimal)

Been researching but haven’t found any explanation for the casting issue.

The error message says that you are trying to call round using 2 integers. This is not possible. Your method only accepts Double or BigDecimal for the first argument. Otherwise your code works fine.
The problem is that java division of 2 integers (same for short) results in an integer result, not a double. You need to add a cast.

Why does it work when the very same method have non nullable args?

Java unlike kotlin automatically converts between primitive number types. This is not the case for their classes. This means that if you have a function like this

void foo(double d) {}

you can call it with

int i = 5;
foo(i);

Nullable numbers in kotlin aren’t represented as primitives. They use their corresponding class. Double is the same as java double and Double? is the same as javas Double. Non nullable number types (int, short, long, float, double) are represented as their primitive versions. However primitive types can’t be null so if you use a nullable number type they are now represented by an object of their class.

1 Like