typestar

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

  1. abstract type Instrument end has no fields, only meaning.
  2. Camera <: Instrument declares the subtype relation.
  3. A generic method covers the family; a specific one overrides.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Types, step 17 of 27 in Language basics.

← Previous Next →