dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.09k stars 1.56k forks source link

Make double automatically coerce integers into doubles #35497

Open lukepighetti opened 5 years ago

lukepighetti commented 5 years ago

int can only accept integers and can only be typed in source as an integer num is any number and seems to be falling out of favor and can accept double or int and can be typed in source as a double or integer double can only accept doubles but can be typed in source as a double or integer

I suggest that we depreciate num and allow doubles to accept either doubles or integers in both source and in code without breaking so that we can stop having our dart apps crash due to javascript services returning floats as integers sometimes.

The reason for num existing is becoming less clear and doubles are becoming more fragile

lrhn commented 5 years ago

Nothing has changed recently with doubles and integers except for adding a slightly shorter syntax for double literals. I agree that num is rarely useful, except as an argument type for, e.g., int.operator+.

The suggestion to make double a super-type of int is unlikely to be viable in practice. The values of integers and doubles are different (except when compiled to JavaScript). There are integer values that cannot be represented exactly as a double. For example 0x7000000000000001 is a valid integer literal, but there is no actual (IEEE-754) double with that value.

If we just rename double to _double and num to double, then you will have exactly the same problems as now, just less control over them because you don't have a type that only contains 64-bit floating point numbers.

lukepighetti commented 5 years ago

Does running every number that comes from a JSON API through double.parse() cause any performance issues?

The problem I am trying to solve is that 99% of the web uses JSON APIs, and 100% of those will return an integer instead of a double if it happens to be a whole number. When this happens, Dart explodes unless you are running every single number through double.parse() or just using num

Cheers

mraleph commented 5 years ago

@lukepighetti if you know that you need a double and you have a num (either int or double) then you can just use num.toDouble in places where you need a double.

lukepighetti commented 5 years ago

It's not really clear to me what the downsides of using num are. From what I can tell it's just a double that doesn't explode when a JSON API sends an integer instead of a decimal. That was my reason for saying we should just throw out double all together and use num instead since it's more robust when dealing with JSON APIs. I'm 99% sure I'm missing something important, for what its worth!