[Note] Types of type systems

1 minute read

Dynamic and static typing

With static typing, type checking is performed at compile time. Dynamic typing, on the other hand, defers type checking to the run time, so type mismatches become run-time error.

Dynamic typing does not impose any typing constraints at compile time.

Weak and strong typing

Note that although a type system is either dynamic (type checking at run time) or static(type checking at compile time), its strength lies on a spectrum: the more implicit conversions it performs, the weaker it is.

e.g.

C:

1float f = 1.234;
2int n = *(int*) &f;

变量类型需要显式声明(静态)

可以各种不讲理地强转(弱类型,因为只有值不知道自己是啥类型才能各种强转不抛异常)

Java:

1Cat cat = new Cat();
2Dog dog = (Dog) cat;  // 异常

类型需要显式声明(静态)

不兼容类型强转会抛异常(强类型)

Ruby:

1n = 1
2n << 1  #=> 2
3
4n = []
5n << 1  #=> [1]

变量无类型,给它什么值都接受(动态)

对象自己知道自己什么类型,并做出相应的行为(强类型)

JavaScript:

1var a = [];
2var n = 1;
3a + n  //=> 1

变量没类型,值自己也不知道自己啥类型