Kotlin Types, Subtypes, and Supertypes vs Classes, Subclasses and Superclasses

Viewed 1084

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?

1 Answers

Types are not the same thing as classes. Types are used to restrict values of variables, properties and function parameters, or function return values. The type might match a class, but it might also match an interface.

A class can have only one direct superclass, but a type can have many direct supertypes, which might be any of

  • The direct superclass of a class type, and any superclass of that superclass, etc. up to Any
  • Interfaces that a class type implements, and superinterfaces of those interfaces
  • Superinterfaces of interface types
  • Any, even if the type is an interface type (interfaces don't have a superclass)
  • Nullable versions of the type or any supertype

And subtypes would be

  • Subclasses, or subclasses of those subclasses, etc. of a class type
  • Subinterfaces of an interface type
  • The non-null version of a nullable type or its subtypes.
  • The Nothing object which is treated as a subtype of everything.

In your example, Number is not a superclass of Int. It is an interface, so it is only a supertype. The direct superclass of Int is Any.

Related