Julia Union Types
A union type is a type that accepts values from two or more types. It lets one spot hold values of different kinds.
A union accepts either member type
Union{Int, String} accepts integers and text. It does not accept decimal numbers.
u = Union{Int, String}
println(5 isa u)
println("hi" isa u)
println(2.5 isa u)Promotion finds a shared type
Int and Float64 share Float64. Int and String share only Any.
println(promote_type(Int, Float64))
println(promote_type(Int, String))A mixed list holds both kinds
The list holds an integer, text, and another integer. Its length is 3.
v = Union{Int, String}[1, "two", 3]
println(v[1])
println(v[2])
println(length(v))Example
describe(x::Union{Int, String}) = x isa Int ? x + 10 : x * "!"
println(describe(5))
println(describe("hi"))Key points
- Union type: a union type accepts values from two or more types.
- Union form: Union{Int, String} accepts integers and text.
- Mixed value: a value of a union type is one of its member types.
- Promotion: promote_type finds a shared type for two types.
- Mixed list: a Vector{Union{Int, String}} can hold integers and text.
In this example, describe accepts an integer or text. The integer 5 gains 10, and the text hi gains an exclamation mark.
Note
promote_type(Int, Float64) is Float64.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Which value fits Union{Int, String}?