Saturday 11 February 2017

Kotlin Literals

Kotlin is a nice language and has many improvements over Java. But not everything is better. I'm not really happy with the literals for example. Let's looks at the following example code:

println(-3.plus(4))

What does this code print? Please make a guess.

...

Should be easy enough, right? -3 plus 4 is 1 obviously. Well, if you try it, you'll see that it prints -7. Why? Because Kotlin interprets this as -(3.plus(4)). Which means that there are no negative literals in Kotlin, only positive ones and the minus is actually the unary negation operator.

This also causes other problems. Let's try to write the minimum Long value as a literal.
println(-9223372036854775808)
The corresponding line in Java works just fine, so Kotlin shouldn't have a problem, right? Wrong! This code doesn't compile. The compiler gives the unhelpful error message "The value is out of range" although the value fits into a Long. Problem is again, that the positive long value 9223372036854775808 really is out of range and Kotlin doesn't understand this as a negative literal but as a positive value with a negation operator. What's the workaround?
println(-9223372036854775807 - 1) // Ugly, but works
Interestingly, the Integer version of this problem works fine.
val foo: Int = -2147483648
Following the Kotlin compiler logic, this line should fail because 2147483648 can only be a Long value and a negative Long value should also be a Long value. But apparently there is some compiler hack in place that prevents this problem for Ints. Why they included the hack for Ints but not for Longs? No idea.

More Kotlin literal shortcomings are listed in the next post.

No comments:

Post a Comment