TExcelTAD
Home › Julia › Julia Conversion & Promotion

Julia Conversion & Promotion

When you write 1 + 2.5, Julia must add an Int64 and a Float64. It does so through two mechanisms: conversion turns a value into another type, and promotion finds a common type for several values and converts them all to it. Both are ordinary Julia code you can extend for your own types.

Conversion

convert(T, x) returns x as a value of type T. It's called automatically in a few places: assigning to a typed field or array element, and assigning to a variable declared with a type.

julia · try it yourself
println(convert(Float64, 3))
println(convert(Int, 4.0))
println(typeof(convert(Rational{Int}, 0.5)), " ", convert(Rational{Int}, 0.5))

v = Float64[]
push!(v, 7)               # Int converted to Float64 automatically
println(v)

try
    convert(Int, 4.5)
catch e
    println(sprint(showerror, e))
end
3.0
4
Rational{Int64} 1//2
[7.0]
InexactError: Int64(4.5)

Conversion must not lose information: convert(Int, 4.5) fails. Conversion also isn't parsing — convert(Int, "42") is a MethodError; use parse(Int, "42").

You want Use
Change number type exactly convert(T, x) or T(x)
Round to an integer type round(Int, x), floor(Int, x), trunc(Int, x)
Text to number parse(T, s) / tryparse(T, s)
Anything to text string(x)

Promotion

promote(a, b, ...) converts its arguments to a common type and returns them as a tuple. promote_type computes that type without values:

julia · try it yourself
println(promote(1, 2.5))
println(promote(1, 2//3))
println(promote(1, 2.0f0, 3//4))
println(promote_type(Int64, Float64))
println(promote_type(Int8, Int32), " ", promote_type(Float32, Int64))
println(typeof([1, 2.5, 3//1]))
(1.0, 2.5)
(1//1, 2//3)
(1.0f0, 2.0f0, 0.75f0)
Float64
Int32 Float32
Vector{Float64}

This is how arithmetic on mixed types works. Base doesn't define +(::Int, ::Float64) directly; it defines a catch-all method that promotes and retries:

julia
+(x::Number, y::Number) = +(promote(x, y)...)

Array literals use the same rules, which is why [1, 2.5, 3//1] becomes a Vector{Float64}.

Making your own type convertible

Suppose we have a Meters type. Adding a convert method lets Julia insert values automatically where a Meters is expected:

julia · try it yourself
struct Meters <: Real
    value::Float64
end
Base.show(io::IO, m::Meters) = print(io, m.value, " m")

struct Feet
    value::Float64
end

Base.convert(::Type{Meters}, f::Feet) = Meters(f.value * 0.3048)

track = Meters[]
push!(track, Meters(100))
push!(track, Feet(328.084))          # converted on insertion
println(track)
println(convert(Meters, Feet(10)))
Meters[100.0 m, 100.00000320000001 m]
3.048 m

Promotion rules for your types

To make mixed arithmetic work, add promotion rules (which type wins) and conversion methods (how to get there), then define the operation once for the common type:

julia · try it yourself
struct Cents <: Real
    n::Int
end
Base.show(io::IO, c::Cents) = print(io, c.n, "¢")

Base.:+(a::Cents, b::Cents) = Cents(a.n + b.n)
Base.convert(::Type{Cents}, x::Integer) = Cents(100x)   # whole dollars
Base.promote_rule(::Type{Cents}, ::Type{<:Integer}) = Cents

println(Cents(250) + Cents(99))
println(Cents(250) + 3)      # 3 is promoted to Cents(300)
println(2 + Cents(5))
println(promote_type(Cents, Int))
349¢
550¢
205¢
Cents

We never wrote +(::Cents, ::Int). Because Cents <: Real, the generic +(::Number, ::Number) method promotes both arguments to Cents and calls our +(::Cents, ::Cents). You only need one promote_rule; Julia applies it symmetrically.

Constructors vs convert

T(x) (calling the type) and convert(T, x) often give the same result, but they mean different things: a constructor builds a new object from arguments, while convert says "this value is a T in another form". For example, Vector{Int}(undef, 3) creates an array, and is not a conversion of anything.

Test yourself

What is promote(2, 0.5)?

  1. (2, 0.5)
  2. (2.0, 0.5)
  3. (2, 0)
  4. 2.5

What does convert(Int, "7") do?

  1. Returns 7
  2. Throws a MethodError: use parse for strings
  3. Returns 55, the code of '7'
  4. Returns nothing

Which function tells Julia which type wins when two types meet in arithmetic?

  1. convert
  2. promote_rule
  3. supertype
  4. typejoin