问题
Haxe seems to assume that certain things must be Int
. In the following function,
class Main {
static function main() {
function mult_s<T,A>(s:T,x:A):A { return cast s*x; }
var bb = mult_s(1.1,2.2);
}
}
I got (with Haxe 3.01):
Main.hx:xx: characters 48-49 : mult_s.T should be Int
Main.hx:xx: characters 50-51 : mult_s.A should be Int
Can anyone please explain why T
and A
should be Int
instead of Float
?
A more puzzling example is this:
class Main {
public static function min<T:(Int,Float)>(t:T, t2:T):T { return t < t2 ? t : t2; }
static function main() {
var a = min(1.1,2.2); //compile error
var b = min(1,2); //ok
}
}
I can't see why t<t2
implies that either t
or t2
is Int. But Haxe seems prefer Int
: min
is fine if called with Int
's but fails if called with Float
's. Is this reasonable?
Thanks,
回答1:
min<T:(Int,Float)>
means T
should be both Int
and Float
. See the constraints section of Haxe Manual.
Given Int
can be converted to Float
implicitly, you can safely remove the constraint of Int
. i.e. the following will works:
http://try.haxe.org/#420bC
class Test {
public static function min<T:Float>(t:T, t2:T):T { return t < t2 ? t : t2; }
static function main() {
var a = min(1.1,2.2); //ok
$type(a); //Float
trace(a); //1.1
var b = min(1,2); //ok
$type(b); //Int
trace(b); //1
}
}
来源:https://stackoverflow.com/questions/21518458/haxe-should-be-int-error