Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 40 ยท Types and Dispatch

The Type System

Understand Julia's type system: abstract and concrete types, the type hierarchy, typeof, isa, subtyping with <:, Union types and the special type Any.

Every value in Julia has a type. The number 3 is an Int64, the text "hi" is a String, and the range 1:3 is a UnitRange{Int64}. Types are not decoration: the compiler uses them to pick the right method, to generate fast machine code, and to catch a whole class of mistakes. Almost everything interesting in Julia, from multiple dispatch to performance, is built on the type system.

Julia is dynamically typed: you never have to write a type, and variables can hold anything. But it is also a language where types are first-class citizens that you can inspect, compare and organize into hierarchies. In this lesson you will learn how to ask a value for its type, how the hierarchy of numbers is arranged, how abstract and concrete types differ, and how to describe "one of several types" with Union.

The site cannot run Julia, so the Julia code in this lesson is read-only and the output is shown in comments. The runnable examples are Python stand-ins that mirror the ideas, and each one says what is real Julia and what is only an analogy.

Asking for a type

typeof returns the concrete type of a value, and isa tests whether a value belongs to a type:

JULIA
typeof(3)          # Int64
typeof(3.0)        # Float64
typeof("hi")       # String
typeof('a')        # Char
typeof(true)       # Bool
typeof(1:3)        # UnitRange{Int64}
typeof([1, 2, 3])  # Vector{Int64} (an alias for Array{Int64, 1})
typeof(nothing)    # Nothing

3 isa Int64        # true
3 isa Number       # true
3 isa String       # false

On a 64-bit machine the default integer is Int64; on a 32-bit machine it is Int32. The names Int and UInt always mean "the integer type of this machine".

Types are values too. typeof(Int64) is DataType, so you can pass types to functions, store them in variables and compare them.

The type hierarchy

Julia types form a tree. Every type has exactly one supertype, and the root of the tree is Any. The function supertype walks one step up:

JULIA
supertype(Int64)    # Signed
supertype(Signed)   # Integer
supertype(Integer)  # Real
supertype(Real)     # Number
supertype(Number)   # Any
supertype(Any)      # Any (the root points at itself)

The operator <: reads as "is a subtype of". Int64 <: Integer is true, and Int64 <: AbstractFloat is false. subtypes goes the other way and lists the direct children:

JULIA
Int64 <: Integer          # true
Float64 <: Real           # true
Float64 <: Integer        # false
subtypes(Integer)         # includes Bool, Signed and Unsigned
subtypes(AbstractFloat)   # includes Float16, Float32, Float64 and BigFloat

The next picture shows the part of the tree you will meet most often.

The number tree

Any The root. Every value is an Any.
Number Abstract parent of all numeric types.
Real Integers, floats and rationals.

Each type has exactly one supertype.

1 / 3

Abstract and concrete types

There are two kinds of types, and the difference matters:

  • A concrete type such as Int64, Float64 or String describes how values are stored. You can create values of it, and it can never have subtypes.
  • An abstract type such as Number, Real or Integer has no instances of its own. It is a name for a group of types, used to write code that accepts many of them.

You can check which is which:

JULIA
isconcretetype(Int64)    # true
isconcretetype(Number)   # false
isabstracttype(Number)   # true
isabstracttype(Int64)    # false

This split explains a rule that surprises newcomers: the type of a value is always concrete. typeof(3) is Int64, never Integer. Abstract types only appear in signatures and annotations, where they mean "anything in this family".

You declare your own abstract type with abstract type ... end, and say that a type belongs to it with <::

JULIA
abstract type Animal end

struct Dog <: Animal
    name::String
end

struct Cat <: Animal
    name::String
end

Dog("Rex") isa Animal   # true
Dog <: Animal           # true
supertype(Dog)          # Animal

A function can now say describe(a::Animal) and accept both. The details of struct follow in Structs and Custom Types.

Type annotations with ::

The double colon has two jobs. In a function signature or a field, it restricts what is accepted. On a local variable inside a function, it declares the type:

JULIA
function double(x::Int)
    return 2x
end

double(4)      # 8
double(4.5)    # MethodError: no method matching double(::Float64)

Annotations on arguments do not make the code faster by themselves. Julia compiles a specialized version for the actual argument types either way. Their job is to choose between methods and to document intent. Do not over-annotate: writing x::Int when x::Integer or no annotation would also work only makes your function less reusable.

Used in an expression, expr::T is a type assertion: it checks the type and throws a TypeError if the check fails.

JULIA
(3 + 4)::Int      # 7
(3 + 4.0)::Int    # TypeError: in typeassert, expected Int64, got a value of type Float64

Union types

Union{A, B} is the type of "a value that is an A or a B". The most common union by far is Union{T, Nothing}, used for values that may be missing:

JULIA
Union{Int, String}        # an Int or a String
Union{Int, Nothing}       # an optional Int

function find_index(xs, target)::Union{Int, Nothing}
    for (i, x) in enumerate(xs)
        x == target && return i
    end
    return nothing
end

find_index([10, 20, 30], 20)   # 2
find_index([10, 20, 30], 99)   # nothing

Julia is good at small unions. The compiler can generate fast code for Union{Int, Nothing} by checking which case it has at runtime. Large unions are a different story: they push the compiler toward slower, generic code, which the performance chapter returns to.

Two special types sit at the extremes of the lattice. Any is the top: every value is an Any, and an unannotated argument is implicitly ::Any. Union{} is the bottom: a type with no values, which is the "type" of an expression that never returns, such as a call to error.

Parametric types, a first look

Many types take parameters in curly braces. Vector{Int64} is a vector whose elements are Int64, and Dict{String, Int64} maps strings to integers. The parameter is part of the type, so the compiler knows exactly what is inside a container:

JULIA
typeof([1, 2, 3])          # Vector{Int64}
typeof([1.0, 2.0])         # Vector{Float64}
typeof([1, "two"])         # Vector{Any}
typeof(Dict("a" => 1))     # Dict{String, Int64}

The last-but-one line is a performance warning: mixing types gives a Vector{Any}, which stores pointers to boxed values and is much slower than a Vector{Int64}. Writing your own parametric types comes in Parametric Types and Generic Code.

A hierarchy you can run

Python has no abstract/concrete split, but class inheritance gives a faithful picture of the hierarchy. This stand-in builds the number tree with classes and uses issubclass as the analogue of <:.

Python A number tree in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is only an analogy. In Julia, <: works on types the compiler knows about, and a concrete type like Int64 can never be subclassed, while a Python class can.

Python's typing.Union plays the role of Union{A, B}. In the next stand-in a function accepts a union and branches on the actual type, which is what Julia does for you automatically through dispatch.

Python A union and a missing value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python never checks these annotations while running; they are hints for tools. In Julia the types are real, and the compiler uses them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does typeof(3) return on a 64-bit machine?

    typeof always returns a concrete type. Integer, Real and Number are abstract, so they can appear in annotations but never as the type of a value.
  2. 2. Which statement about abstract types is true?

    Abstract types describe families such as numbers or integers. Values always have a concrete type, and the abstract type is only used in signatures and annotations.
  3. 3. What is Float64 <: Integer?

    Float64 sits under AbstractFloat, which sits under Real. Integer is a sibling branch, so Float64 is not a subtype of it.
  4. 4. What is the type Union{Int, Nothing} typically used for?

    Union{T, Nothing} is the usual way to say "an optional T". Functions such as a search can return nothing when no match exists.
  5. 5. Why is [1, "two"] a Vector{Any}?

    Julia picks a common element type for the literal. Integers and strings only share Any, and a Vector{Any} is slower than a Vector{Int64}.

Summary

  • Every value has a concrete type, found with typeof; isa and <: test membership and subtyping.
  • Types form a tree rooted at Any; supertype and subtypes walk it.
  • Abstract types name families and cannot have instances; concrete types hold data and cannot have subtypes.
  • abstract type Name end and struct X <: Name build your own hierarchies.
  • :: restricts arguments and fields, or asserts a type in an expression.
  • Union{A, B} means one of several types, and Union{T, Nothing} is the standard optional value.
  • Parameters such as Vector{Int64} are part of the type, and mixed element types fall back to Any.

Next, learn to define your own data types in Structs and Custom Types.