💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
类型参数可以被约束为多种类型: > Type parameters can be constrained to multiple types: ~~~ typedef Measurable = { public var length(default, null):Int; } class Main { static public function main() { trace(test([])); trace(test(["bar", "foo"])); // String should be Iterable<String> //test("foo"); } static function test<T:(Iterable<String>, Measurable)>(a:T) { if (a.length == 0) return "empty"; return a.iterator().next(); } } ~~~ 方法test的类型参数T被约束为Iterable<String>和Measurable。后者方便起见被使用一个 typedef(第3.1节)定义,需要兼容有一个只读(第4.2节)的Int类型length属性的类型。约束然后说一个类型是兼容的,如果: > Type parameterT of method test is constrained to the types Iterable<String> and Measurable. The latter is defined using a typedef (3.1) for convenience and requires compatible types to have a read-only property (4.2) named length of type Int. The constraints then say that a type is compatible if * 和 Iterable<String>兼容 * 并且有一个Int类型的length属性 > * it is compatible with Iterable<String> and > * has a length-property of type Int. 我们可以看到,在第7行调用test并传递一个空的数组,和第8行一个Array<String>是没有问题的。因为数组都有length属性和一个 iterable 方法。然而,传递一个字符串作为参数,如第9行则会导致约束失败,因为字符串不兼容 Iterable<T>。 > We can see that invoking test with an empty array in line 7 and an Array<String> in line 8 works fine. This is because Array has both a length-property and an iterator-method. However, passing a String as argument in line 9 fails the constraint check because String is not compatible with Iterable<T>.