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:
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?
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
Any
Any
, even if the type is an interface type (interfaces don't have a superclass)And subtypes would be
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With