double.clamp should return a double

I ran into two issues independently recently that both led me to the same conclusion: double.clamp should just always return a double.

Issue 1: removal of implicit casts (cc @a14n @goderbauer)

Without implicit casts, double.clamp needs continuous babysitting with as to make it work:

  // assume implicit casts are disabled for this code
  void foo(double x) { }
  void main() {
    double y = 1.1;
    foo(y.clamp(0.0, 1.0) as double); // without the as double, this is a compile-time error
  }

It’s absurd that you keep having to cast things to double when you are only dealing with doubles.

This is newly important since implicit casts are going away with NNBD.

Issue 2: Accidental ints

Because int literals can masquerade as doubles, it’s common to use them. Because clamp takes nums, they don’t get considered as doubles there. Because clamp returns its value directly, what appears to just be code dealing in doubles is actually suddenly dealing with ints, which leads to runtime errors:

  void foo(double x) { }
  void main() {
    double y = 1.1;
    foo(y.clamp(0, 1).toDouble()); // without the toDouble, this is a runtime error
  }

Author: Fantashit

1 thought on “double.clamp should return a double

  1. You could solve issue 2 above by implying toDouble on the return value, that would be backwards-compatible (may require compiler work to keep it efficient).

    Issue 1 is going to become seriously problematic with NNBD. We’re already experiencing this in Flutter to the point that we’re discussing creating an extension method on double that has the right signature and just using that. It would be very unfortunate if Flutter had to do that given that we’re all one team. 🙁

Comments are closed.