Haxe隐式强制转换基于Haxe.ds的抽象.或者将Class作为类型



我想使用本文中描述的方法:https://code.haxe.org/category/other/passing-different-types-to-a-function-parameter.html

只要我提供";混凝土;类型,但问题是我想使用Class<String>作为OneOf<A, B>中的类型之一。

像这里:

import haxe.ds.Either;
abstract OneOf<A, B>(Either<A, B>) from Either<A, B> to Either<A, B> {
@:from inline static function fromA<A, B>(a:A):OneOf<A, B> {
return Left(a);
}
@:from inline static function fromB<A, B>(b:B):OneOf<A, B> {
return Right(b);
}
@:to inline function toA():Null<A>
return switch (this) {
case Left(a): a;
default: null;
}
@:to inline function toB():Null<B>
return switch (this) {
case Right(b): b;
default: null;
}
}
class Test {
static function main() {
Test.test(String);
}
static public function test(a:OneOf<Class<String>, Int>) {}
}

或者在这里举个例子:https://try.haxe.org/#d12d5c07

它给出编译错误:

Test.hx:27: characters 13-19 : Class<String> should be OneOf<Class<String>, Int>
Test.hx:27: characters 13-19 : ... For function argument 'a'

这可能与Class<T>也是一个抽象的事实有关。

是否有任何变通方法可以不传递类的实例,而是将此类的类型传递给OneOf

在Haxe 4中,您可以使用EitherType,只要选项不是两个不同的Class<T>

import haxe.extern.EitherType;
class Test {
static function test(val:EitherType<Class<String>, Int>) {
if (val is Int) {
trace('int: $val');
} else {
trace('class: $val');
}
}
static function main() {
test(4);
test(String);
}
}

Test.hx:6:int:4
Test.hx:8:class:{__name__:true}

对于您的代码,显式执行OneOf.fromA是可行的,但不太方便——也许这是类型检查的一个错误。

相关内容

最新更新