Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 40 ยท Types and Dispatch

Parametric Types and Generic Code

Write generic Julia code with parametric types, where clauses and type parameters, understand invariance and Vector{T}, and rely on duck typing safely.

A Vector{Int64} and a Vector{String} are both vectors, yet the compiler treats them as different types so it can store each compactly and run fast. The thing in curly braces is a type parameter. Parametric types let one definition serve many element types, and where clauses let one function work for all of them without any copying or macros.

This lesson shows how to read and write parametric types, how where works, why Vector{Int} is not a Vector{Number}, and how to write generic algorithms. Everything in Julia here is read-only on this site; the Python stand-ins mirror the ideas with generics and duck typing.

Type parameters you already use

You have met parametric types without defining any:

JULIA
Vector{Int64}              # a one-dimensional array of Int64
Matrix{Float64}            # a two-dimensional array of Float64
Dict{String, Int}          # keys are String, values are Int
Pair{Symbol, Float64}      # a key => value pair
Tuple{Int, String, Bool}   # a fixed-size, mixed tuple
NTuple{3, Int}             # shorthand for Tuple{Int, Int, Int}
Array{Float64, 2}          # the long name of Matrix{Float64}

Parameters are usually types, but they can be plain values too, as in the 2 of Array{Float64, 2} (the number of dimensions) or the 3 of NTuple{3, Int}. Because the information is in the type, the compiler knows the layout of the data without checking it at run time.

Defining a parametric struct

Add parameters after the type name, then use them in the fields:

JULIA
struct Box{T}
    item::T
end

Box(3)            # Box{Int64}(3)
Box("hello")      # Box{String}("hello")
Box(2.5)          # Box{Float64}(2.5)
typeof(Box(3))    # Box{Int64}

Julia infers T from the argument, so you rarely write Box{Int64}(3) yourself. A more realistic example is a pair of coordinates of any numeric type, with the parameter restricted:

JULIA
struct Point{T<:Real}
    x::T
    y::T
end

Point(1, 2)        # Point{Int64}(1, 2)
Point(1.5, 2.5)    # Point{Float64}(1.5, 2.5)
Point(1, 2.5)      # MethodError: both fields must share T
Point("a", "b")    # MethodError: String is not a subtype of Real

T<:Real is a bound: T may be any subtype of Real. Both fields use the same T, which guarantees they have the same type, and since the struct is concrete the fields are stored inline with no boxing. Mixed input like Point(1, 2.5) fails because no constructor fits; you can add an outer constructor that promotes the arguments, using promote.

What a type parameter buys

One definition Box{T} covers every element type.
Speed The compiler knows the exact layout.
Safety Fields with the same T always match.
1 / 2

Generic functions with where

A method signature uses where to introduce type variables:

JULIA
function first_or(v::Vector{T}, default::T) where T
    return isempty(v) ? default : v[1]
end

first_or([4, 5, 6], 0)     # 4
first_or(Int[], 0)         # 0
first_or(["a"], 1)         # MethodError: T cannot be both String and Int

The method applies only when the vector's element type and the default have the same type T. A bound narrows it further:

JULIA
function mean_of(xs::AbstractVector{T}) where T<:Real
    return sum(xs) / length(xs)
end

mean_of([1, 2, 3, 4])      # 2.5
mean_of([1.5, 2.5])        # 2.0

Note the use of AbstractVector: writing Vector{T} would reject ranges, views and other vector-like types. Accepting the abstract type makes your function usable by far more callers, which the interfaces lesson builds on.

The same syntax works for a bare type variable: f(x::T, y::T) where T means "both arguments have the same type", and f(x::Vector{<:Number}) is shorthand for a vector of any subtype of Number.

Invariance: Vector{Int} is not Vector{Number}

This rule surprises almost everyone. Although Int <: Number, you have:

JULIA
Int <: Number                  # true
Vector{Int} <: Vector{Number}  # false
Vector{Int} <: Vector{<:Number}  # true

Parametric types are invariant: Vector{Int} and Vector{Number} are unrelated. The reason is that a Vector{Number} could hold a Float64, and if Vector{Int} counted as one you could smuggle a float into an integer vector. A method taking Vector{Number} therefore rejects a Vector{Int}:

JULIA
total(v::Vector{Number}) = sum(v)
total([1, 2, 3])               # MethodError

The cure is the <: wildcard, written Vector{<:Number}, or a where clause. Both mean "a vector of some subtype of Number" and accept Vector{Int}.

Writing generic algorithms

A generic function avoids hard-coding types. The typical tricks:

  • Use zero(T), one(T) and eltype(xs) instead of literal 0 and 1.
  • Use promote_type or promote when mixing types.
  • Take abstract types (Number, AbstractVector) in signatures, or none at all.
JULIA
function mysum(xs)
    total = zero(eltype(xs))
    for x in xs
        total += x
    end
    return total
end

mysum([1, 2, 3])           # 6 (an Int)
mysum([0.5, 0.25])         # 0.75 (a Float64)
mysum(1//2 .* [1, 2, 3])   # 3//1 (a Rational)
mysum(Int[])               # 0, because zero(Int) is the start value

With total = 0 this would still work, but it would start as an Int and then become a Float64, a type change that costs speed. Starting with zero(eltype(xs)) keeps the accumulator one type throughout.

Duck typing

Because Julia does not require annotations, code with no annotations at all is perfectly generic. If it can use +, < or length on its arguments, it works: "if it quacks like a duck." The annotations you add are there to pick between methods and to document intent, not to make the code work. A good habit: annotate only as strictly as the algorithm needs, and prefer abstract types.

Generics in Python

Python's typing.Generic is the analogue of a parametric struct. It is not enforced at run time, but it expresses the same relationship between a container and its element type.

Python A generic Box and an invariance check

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 happily lets that last call corrupt the list, which is exactly the hole Julia's invariance closes. In Julia, Vector{Int} can never receive a Float64 that way.

The next stand-in shows duck typing: one function that works for ints, floats, fractions and complex numbers because it only relies on + and a zero of the right kind.

Python One generic sum for many types

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.

In Julia the compiler generates a separate, optimized version of mysum for each element type the first time you call it. Python runs the same bytecode every time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Box(3) produce for struct Box{T}; item::T; end?

    Julia infers T from the argument. The value 3 is an Int64, so T is Int64 and the full type is Box{Int64}.
  2. 2. Is Vector{Int} <: Vector{Number}?

    A Vector{Number} could hold any number, so accepting a Vector{Int} would allow storing a float in it. Use Vector{<:Number} to accept both.
  3. 3. What does where T<:Real mean in a method signature?

    <: is the subtype bound. The method applies when T is Real or one of its subtypes such as Int64 or Float64.
  4. 4. Why does mysum start with zero(eltype(xs)) rather than 0?

    Starting with an Int 0 for a Float64 vector would change the accumulator's type midway through the loop, which can slow the compiled code.
  5. 5. Which signature accepts a range, a view and a Vector of numbers?

    AbstractVector is the common supertype of vector-like types, while Vector is one concrete array type.

Summary

  • Type parameters in curly braces (Vector{T}, Dict{K, V}) are part of the type and let the compiler lay out data precisely.
  • Define your own with struct Name{T} ... end; add a bound with T<:Real.
  • where introduces type variables in a method signature; the same variable name forces the same type.
  • Parametric types are invariant: use Vector{<:Number} to accept any subtype.
  • Write generic algorithms with zero, one, eltype, promote and abstract argument types.
  • Duck typing works; annotations are for dispatch and documentation, not for correctness.

Next: learn the informal contracts that let your own types plug into for loops and Base in Interfaces and Iteration Protocols.