Consider the following code:
abstract type AbstractTransport end
mutable struct Car <: AbstractTransport
name::String
engine_type::String
number_of_people::Int32
function Car(name::String, engine_type::String, number_of_people::Int32)
# Validation left out.
new(name,engine_type,number_of_people)
end
end
mutable struct StarShip <: AbstractTransport
number_of_people::Int32
function StarShip(number_of_people::Int32)
# Validation left out.
new(number_of_people)
end
end
As you can see both transports are sub types of AbstractTransport
but they don’t have consistent fields. I won’t get an error until I use a method that requires certain fields:
function transport_info(transport::AbstractTransport)
println(transport.name)
println(transport.engine_type)
end
uss_enterprise = StarShip(100)
transport_info(uss_enterprise) # type StarShip has no field name
Is there a way to make certain fields mandatory during construction of sub types? For example in OOP, you would have an Abstract
class that contains all the attributes common to all subclasses. When constructing an object, you would pass the required fields to the Abstract
class using the constructor.
In OOP, I would put the name
and engine_type
in the abstract class, so even if a subclass doesn’t provide new attributes it at least has to provide name
and engine_type
.
I could use hasfields()
but then each method that uses an AbstractTransport
would need to check for the required fields.