Abstract types in Julia
Name the family, dispatch on it, override per concrete type.
# An abstract type names a family; methods dispatch on it.
abstract type Instrument end
struct Camera <: Instrument
megapixels::Int
end
struct Spectrograph <: Instrument
resolution::Int
end
# One generic fallback, one specific override.
setup(i::Instrument) = "generic checklist"
setup(c::Camera) = "cool sensor, $(c.megapixels) MP flat frames"
println(setup(Camera(62)))
println(setup(Spectrograph(1800)))
println(Camera <: Instrument)
How it works
abstract type Instrument endhas no fields, only meaning.Camera <: Instrumentdeclares the subtype relation.- A generic method covers the family; a specific one overrides.
Keywords and builtins used here
CameraInstrumentIntSpectrographabstractendstructtype
The run, in numbers
- Lines
- 17
- Characters to type
- 439
- Tokens
- 75
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 69 seconds.
Step 2 of 3 in Types, step 17 of 27 in Language basics.