1

I am learning about subtypes and supertypes in Kotlin, and initially assumed that these terms meant inherited and parent classes. But after reading this post from JetBrains, I am not sure I understand exactly what they mean by subtyping.

The post explains that Any is a subtype of Any? (makes sense), Number is a subtype of Any, and Int is a subtype of Number. So far so good (Any? -> Any -> Number -> Int), and (Any? -> Number? -> Int?).

But notice diagram # 5:

enter image description here

This diagram (and the accompanying text) imply and explain that Number is a subtype of its nullable counterpart Number?, and that Int is also a subtype of its nullable counterpart Int?. This sounds intuitive, until you remember that Int is also a subtype of Number, and Number a subtype of Any! This is in direct contradiction with the Kotlin docs which specify that

Kotlin supports single-parent class inheritance - so each class (except the root class Any) has got exactly one parent class, called a superclass.

I am left assuming that subtypes are not children classes per se (a single class can be a subtype of more than one parent class at once maybe?). If so, can someone clarify for me exactly what is meant by "subtypes" and "supertypes" in Kotlin?

4

1 回答 1

8

类型与类不同。类型用于限制变量、属性和函数参数的值或函数返回值。类型可能匹配一个类,但它也可能匹配一个接口。

一个类只能有一个直接超,但一个类型可以有许多直接超类型,可以是任何一个

  • 类类型的直接超类,以及该超类的任何超类,等等。Any
  • 类类型实现的接口,以及这些接口的超接口
  • 接口类型的超接口
  • Any,即使类型是接口类型(接口没有超类)
  • 类型或任何超类型的可空版本

子类型将是

  • 类类型的子类或这些子类的子类等
  • 接口类型的子接口
  • 可空类型或其子类型的非空版本。
  • Nothing被视为一切子类型的对象。

在您的示例中,Number不是Int. 它是一个接口,所以它只是一个超类型。的直接超类IntAny

于 2020-09-23T18:12:56.193 回答