liveBook · Manning

Type safety

As explained in Julia as a Second Language

Type safety is the property that a programming language prevents operations from being applied to values in incompatible ways.

Type safety helps catch values that do not fit an intended category or operation. In Julia, enumerations restrict a category to named values, while parametric types can restrict the values stored in a composite type. These checks can catch mistakes at runtime. section 13.5.1 section 18.0

Keep a category closed

With `@enum DriveStyle hex phillips slotted torx`, `DriveStyle(2)` produces `slotted`, but `DriveStyle(4)` raises an `ArgumentError`. A drive style cannot be created from an unspecified value. section 13.5.1

A type parameter can require two fields to share a type. `struct PVec2D{T} Δx::T; Δy::T end` accepts `PVec2D(2, 3)`, but cannot infer one `T` for `PVec2D(2, 3.0)`. Supplying `PVec2D{Int}(2, 3.0)` instead specifies the field type and converts the second value. section 18.3

Listing 18.7 Point and Vec2D defined so the type parameter must be a number type
import Base: +, -
 
struct Point{T<:Number}
    x::T
    y::T
end
 
struct Vec2D{T<:Number}
    Δx::T
    Δy::T
end
 
"Adding vector `v` to point `p` creates a new point"
function +(p::Point{T}, v::Vec2D{T}) where T
    Point(p.x + v.Δx, p.y + v.Δy)
end
 
"Subtracting two points gives a vector"
function -(p::Point{T}, q::Point{T}) where T
    Vec2D(p.x - q.x, p.y - q.y)
end

For coordinates, `T<:Number` goes further: it rules out character-valued points and vectors. The `where T` methods also require their arguments to use the same coordinate type; a method can use separate parameters when that restriction is too tight. section 18.3

Choose constraints that reflect the values an operation should accept, rather than making every type as narrow as possible. Parametric types can also help the compiler optimize code and lay out collections in memory with less boxing. section 18.3 section 18.6

How Julia as a Second Language covers it

How deep it goes
Demonstrates runtime errors, shared field types, explicit conversion, numeric bounds, and method signatures through Julia examples.
Examples
Contrasts valid and invalid drive styles, mixed-type vector coordinates, and points and vectors constrained to numeric coordinates.
What it assumes
Assumes familiarity with using typed collections and introduces defining custom parametric types through 2D geometry.
What you can do after
Build it from scratch with enumerations and constrained parametric types to catch unsuitable values at runtime.
How it connects
Connects type safety to enumerations, parametric types, subtyping, method signatures, boxing, and memory layout.

Also explained in

Compare how 8 books explain type safety →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.