HaxeFoundation / haxe

Haxe - The Cross-Platform Toolkit
https://haxe.org
6.14k stars 656 forks source link

to Float on abstract is getting ignored, can't do math operations #11576

Open Jarrio opened 7 months ago

Jarrio commented 7 months ago
class Test {
  static function main() {
    var now = Date.now().getTime() - Foo.a;
    trace(now);
  }
}

enum abstract Foo(Float) to Float {
    var a = 10000001;
}

This results in the following error:

[ERROR] Test.hx:3: characters 38-43

 3 |     var now = Date.now().getTime() - Foo.a;
   |                                      ^^^^^
   | Foo should be Int

But everything here is typed and declared as Float so why is it that I can't do the subtraction?

filt3rek commented 7 months ago

Hej,

It works with that :

enum abstract Foo(Float) from Float to Float {
    var a : Float = 10000001;
}

But I agree it would be cool if it did the conversion by itself

Jarrio commented 7 months ago

Yes, there are ways to get around it but it changes what the intention of the code is, I don't want to allow any float for Foo.

The solution I do is type hitting Foo at declaration But I don't understand why when I specified that the type should be to Float

kLabz commented 7 months ago

Current workaround is to add @:op there https://try.haxe.org/#B8D0053C or the short version https://try.haxe.org/#C2F8766b (see manual for this one)

ibilon commented 7 months ago

the short version https://try.haxe.org/#C2F8766b

@:commutative can be used to avoid adding add2 and sub2.