Haxe 编译器利用丰富的类型系统,可以在编译时检测程序中类型相关的错误。类型错误是指对一个给定类型执行了一个无效操作,比如,除以一个字符串、尝试访问一个整数的字段,或者调用一个函数而没有传递足够(或太多)的参数。在一些语言中,这些额外的安全性考虑通常需要程序员消耗额外的精力,因为程序员被要求使用显式分配类型的语法结构:
The Haxe Compiler employs a rich type system which helps detect type-related errors in a program at compile-time. A type error is an invalid operation on a given type such as dividing by a String, trying to access a field of an Integer or calling a function with too few (or too many) arguments.
In some languages this additional safety comes at a price because programmers are forced to explicitly assign types to syntactic constructs:
var myButton:MySpecialButton = new MySpecialButton(); // As3
MySpecialButton* myButton = new MySpecialButton(); // C++
显式地类型声明在 Haxe 中并不是必须的,因为编译器可以推断类型:
Explicit type annotations are not required in Haxe, because the compiler can infer the type:
var myButton = new MySpecialButton(); // Haxe
我们会在 类型推断(第3.6节) 中对类型推导的细节进行说明。就目前而言,我们可以肯定的说上面代码中的变量 myButton
是 MySpecialButton
类的一个实例。
We will explore type inference in detail later in Type Inference. For now, it is sufficient to say that the variable
myButton
in the above code is known to be an instance of classMySpecialButton
.
Haxe 的类型系统能识别七个类型组(Type Group):
- 类实例:某个给定的类或者接口的对象
- 枚举实例:Haxe 枚举类型中的一个值
- 结构类型:一个匿名结构,即,一个被命名的字段的集合
- 函数类型:一个由一些参数和一个返回值组成的复合类型
- 动态类型:一个万能类型,可以和任何类型兼容
- 抽象类型:一个编译时类型,会在运行时被一另外一种类型表示
- 单形类型:一个 未知的(unknown) 类型,会在之后转变为一个确定的类型
The Haxe type system knows seven type groups:
- Class instance: an object of a given class or interface
- Enum instance: a value of a Haxe enumeration
- Structure: an anonymous structure, i.e. a collection of named fields
- Function: a compound type of several arguments and one return
- Dynamic: a wildcard type which is compatible with any other type
- Abstract: a compile-time type which is represented by a different type at runtime
- Monomorph: an unknown type which may later become a different type
下一章中,我们将描述这些类型组中的每个类型,以及它们之间的联系。
定义 复合类型: 复合类型是指含有子类型的类型。这其中包括使用了 类型参数(第3.2节) 的任何类型以及 函数类型(第2.6节)。