Why was Double#toShort() deprecated?

The suggested replacement is more explicit, because it has two conversion steps, Double->Int and Int->Short, and each of them is dealing with values out of the target type range in its own way:

  • Double.toInt() clamps a number into the Int range,
  • Int.toShort() discard the highest bits of a number.

On the contrary, the combination of these two approaches in the single function Double.toShort is that counter-intuitive and hardy expected behavior.

Note that JVM doesn’t specify how the conversion from Double to Short should be done, it only provides bytecode instructions to perform some primitive numeric type conversions and even doesn’t have a single instruction to convert a double value to short: Chapter 2. The Structure of the Java Virtual Machine

I agree that the conversion from Double to Short became more verbose in 1.4, so in future, we may introduce the following variants of Double->Short conversion:

  • one that clamps a number into the Short range,
  • one that throws an exception if a number is out of the Short range,
  • one that returns null if a number is out of the Short range.

It’s unlikely that we’ll reintroduce the variant of the conversion that behaves as the one formerly known as Double.toShort().

4 Likes