Subtyping is a popular concept in the OOP paradigm. We define inheritance between two classes by extending the class:
open class Animal(val name: String) class Dog(name: String): Animal(name)
The Dog
class extends the Animal
class, so the Dog
type is a subtype of Animal
. This means that we can use an expression of type Dog
whenever an expression of type Animal
is required; for example, we can use it as a function argument or assign a variable of type Dog
to a variable of type Animal
:
fun present(animal: Animal) { println( "This is ${ animal. name } " ) } present(Dog( "Pluto" )) // Prints: This is Pluto
Before we move on, we need to discuss the difference between class and type. Type is a more general term--it can be defined by class or interface, or it can be built into the language (primitive type). In Kotlin, for each class (for example, Dog
), we have at least two possible types--non-nullable (Dog
) and nullable (Dog?
). What's more, for each generic class...