Julia Abstract and Subtypes
An abstract type is a type name that groups other types under it, without holding values itself. A type placed under it is called a subtype.
Define an abstract type and a subtype
Animal is defined as an abstract type first. Dog is then declared as a subtype of Animal with the <: sign.
abstract type Animal end
struct Dog <: Animal
name::String
end
println(supertype(Dog))The <: check compares two types
Dog <: Animal asks whether Dog is a subtype of Animal. Int is not under Animal, so the second check is false.
abstract type Animal end
struct Dog <: Animal
name::String
end
println(Dog <: Animal)
println(Int <: Animal)isa checks a value against a type
A Dog value counts as an Animal, because Dog is a subtype of Animal. Both checks below print true.
abstract type Animal end
struct Dog <: Animal
name::String
end
dog = Dog("Rex")
println(isa(dog, Dog))
println(isa(dog, Animal))Example
abstract type Animal end
struct Dog <: Animal
name::String
end
struct Cat <: Animal
name::String
end
rex = Dog("Rex")
mia = Cat("Mia")
println(supertype(Cat))
println(isa(rex, Animal))
println(isa(mia, Animal))
println(isa(rex, Cat))Key points
- Abstract type: abstract type Animal end defines the group name Animal.
- Subtype: struct Dog <: Animal makes Dog a subtype of Animal.
- The <: sign: <: reads as "is a subtype of", so Dog <: Animal is true.
- supertype: supertype(Dog) gives the type directly above Dog, which is Animal.
- isa: isa(dog, Animal) reports whether a value belongs to a type or any of its subtypes.
In this example, Dog and Cat are both subtypes of Animal, and supertype(Cat) confirms Animal sits above Cat. The isa checks then show that both values count as Animals, while the Dog value is not a Cat.
Note
a value of a subtype counts as a member of its abstract type in an isa check.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does struct Cat <: Animal declare?