I think the behavior of casting method from signed integer to larger unsigned integer like
Short.toUInt() is not clear from function name because we can think two behaviors below:
- cast to larger signed integer the first then cast to unsigned.
- cast to unsigned integer the first then cast to larger unsigned.
Those behaviors are not same if the value is a negative integer.
In the first behavior, upper bits are filled with 1 but 0 in the second behavior.
In my opinion, this can make many bugs so it should not be used and everyone should explicitly cast in two steps like
So I think those methods should be deprecated.
The sign extending behavior of
Short.toUInt() was chosen because it is common in other languages with unsigned types, such as C, Rust, and Go, see this comment: https://github.com/Kotlin/KEEP/issues/135#issuecomment-450003620
It almost makes sense… except that Kotlin is strongly connected to Java, and Java has the
Short.toUnsignedInt() method that does the exact opposite.
It’s a good thing Kotlin has
UShort now, but it doesn’t always help, especially with Java interop. I still find myself often using
I know many languages use such behavior but I think it’s better to depreciate because it’s confusing.
If Kotlin thinks deprecation is too hard, It also is good to add an optional inspection in Kotlin, In my opinion.