Types and Dispatch

Last updated on 2025-01-12 | Edit this page

Overview

Questions

  • How does Julia deal with types?
  • Can I do Object Oriented Programming?
  • People keep talking about multiple dispatch. What makes it so special?

Objectives

  • dispatch
  • structs
  • abstract types

Julia is a dynamically typed language. Nevertheless, we will see that knowing where and where not to annotate types in your program is crucial for managing performance.

In Julia there are two reasons for using the type system:

  • structuring your data by declaring a struct
  • dispatching methods based on their argument types

Inspection


You may inspect the dynamic type of a variable or expression using the typeof function. For instance:

JULIA

typeof(3)

OUTPUT

Int64

JULIA

typeof("hello")

OUTPUT

String

(plenary) Types of floats

Check the type of the following values:

  1. 3
  2. 3.14
  3. 6.62607015e-34
  4. 6.6743f-11
  5. 6e0 * 7f0
  1. Int64
  2. Float64
  3. Float64
  4. Float32
  5. Float64

Structures


JULIA

struct Point2
  x::Float64
  y::Float64
end

JULIA

let p = Point2(1, 3)
  println("Point at ${p.x}, ${p.y}")
end

Methods

JULIA

dot(a::Point2, b::Point2) = a.x*b.x + a.y*b.y

3d Point

JULIA

struct Point3
  x::Float64
  y::Float64
  z::Float64
end

dot(a::Point3, b::Point3) = a.x*b.x + a.y*b.y + a.z*b.z

Multiple dispatch (function overloading)


JULIA

Base.:+(a::Point2, b::Point2) = Point2(a.x+b.x, a.y+b.y)

JULIA

Point2(1, 2) + Point2(-1, -1)

OUTPUT

Point2(0, 1)

OOP (Sort of)

Julia is not an Object Oriented language. If you feel the unstoppable urge to implement a class-like abstraction, this can be done through abstract types.

JULIA

abstract type Vehicle end

struct Car <: Vehicle
end

struct Bike <: Vehicle
end

function travel_time(v::Vehicle, distance::Float64)
end

function fuel_cost(v::Vehicle, ::Float64)
  return 0.0
end

function fuel_cost(v::Car, distance::Float64)
end

Key Points

  • Julia is fundamentally a dynamically typed language.
  • Static types are only ever used for dispatch.
  • Multiple dispatch is the most important means of abstraction in Julia.
  • Parametric types are important to achieve type stability.