TExcelTAD
Home › Julia › Julia Types

Julia Types

Every value in Julia has a type, and types are organised in a single type hierarchy (a tree). Julia is dynamically typed — types belong to values, not variables — but you can use type annotations to document code, catch mistakes and, above all, to drive multiple dispatch.

julia · try it yourself
for v in (42, 3.14, "hi", 'c', true, [1, 2], (1, "a"), nothing, sqrt)
    println(rpad(repr(v), 10), " :: ", typeof(v))
end
42         :: Int64
3.14       :: Float64
"hi"       :: String
'c'        :: Char
true       :: Bool
[1, 2]     :: Vector{Int64}
(1, "a")   :: Tuple{Int64, String}
nothing    :: Nothing
sqrt       :: typeof(sqrt)

Abstract and concrete types

  • Concrete types (like Int64, Float64, String) can have values (instances). They cannot have subtypes.
  • Abstract types (like Number, Real, AbstractString) cannot be instantiated. They exist to group related types, so functions can accept "any real number".

<: means "is a subtype of". supertype walks up the tree and subtypes (from InteractiveUtils) walks down:

julia · try it yourself
println(Int64 <: Integer, " ", Int64 <: Real, " ", Int64 <: AbstractFloat)
println(isconcretetype(Int64), " ", isconcretetype(Real))

T = Int64
chain = [T]
while T != Any
    global T = supertype(T)
    push!(chain, T)
end
println(join(chain, " <: "))
println(supertype(Float64))
true true false
true false
Int64 <: Signed <: Integer <: Real <: Number <: Any
AbstractFloat

At the top of the tree is Any, the supertype of every type. At the bottom is Union{}, which has no values.

Checking types

Expression Meaning
typeof(x) the concrete type of x
x isa T / isa(x, T) is x an instance of T (or a subtype)?
S <: T is type S a subtype of T?
eltype(collection) the element type
julia · try it yourself
x = 2.5
println(x isa Float64, " ", x isa Real, " ", x isa Integer)
println(eltype([1, 2, 3]), " ", eltype("text"))
println(Vector{Int} <: AbstractVector, " ", String <: AbstractString)
true true false
Int64 Char
true true

Type annotations

The :: operator has two uses. On a function argument it restricts which values are accepted. On an expression it asserts the type at run time. On a local variable declaration it converts assigned values to that type:

julia · try it yourself
half(n::Integer) = n ÷ 2
println(half(9))
try
    half(9.0)
catch e
    println(typeof(e))
end

y = (1 + 2)::Int           # type assertion: passes
println(y)
try
    (1 + 2.0)::Int
catch e
    println(sprint(showerror, e))
end

function as_float()
    total::Float64 = 0     # every assignment converts to Float64
    total = 3
    return total
end
println(as_float())
4
MethodError
3
TypeError: in typeassert, expected Int64, got a value of type Float64
3.0

Annotations on arguments don't make code faster — Julia compiles a specialised version for the actual types anyway. Use them for dispatch and documentation, and keep functions generic (::Real rather than ::Float64) so they work with more types.

Union types and Nothing

Union{A, B} is the type of values that are either A or B. A common pattern is Union{T, Nothing} for a value that might be absent:

julia · try it yourself
function find_user(id)::Union{String, Nothing}
    users = Dict(1 => "ana", 2 => "ben")
    return get(users, id, nothing)
end

for id in (2, 7)
    u = find_user(id)
    println(u === nothing ? "user $id not found" : "found $u")
end
println(Int <: Union{Int, String}, " ", isnothing(nothing))
found ben
user 7 not found
true true

Note: nothing (type Nothing) means "no value", for example from a function with nothing to return. missing (type Missing) is used in data analysis for "a value exists but is unknown"; it propagates through arithmetic: missing + 1 is missing.

Test yourself

Which of these is an abstract type?

  1. Int64
  2. Float64
  3. Real
  4. String

What is 3 isa Number?

  1. true
  2. false
  3. an error
  4. Int64

Why prefer f(x::Real) over f(x::Float64) for a numeric function?

  1. It's faster
  2. It accepts more types (Int, Rational, ...) and Julia still specialises the compiled code
  3. Float64 annotations are not allowed
  4. It avoids conversions to Int