Union type constructor question

Can someone help explain to me why the first line produces an error but the second works? On v1.10.3, thanks!

julia> Union{Int,Symbol}(5)
ERROR: MethodError: no method matching Union{Int64, Symbol}(::Int64)
Stacktrace:
 [1] top-level scope
   @ REPL[36]:1

julia> Union{Int,Float64}(543.435)
543.435

This sounds tautological, but it’s because there was a method for the latter and not the former. You can find out what method:

julia> @which Union{Int, Float64}(543.435)
(::Type{T})(x::T) where T<:Number
     @ Core boot.jl:792

It does nothing though, effectively just letting dispatch check an instance is already of a given Number type: (::Type{T})(x::T) where {T<:Number} = x.

Note that there’s no method naming the particular Union (check methods(Union{Int, Float64})). That is possible but named supertypes like Number are more practical than the arbitrary Unions. Particular Unions important enough to get a const alias may be an exception, but I don’t have an example off the top of my head.

Thanks, I was mentally thinking of these more like sum types but now I understand why this is happening.

There is a SumTypes.jl package, if you’re looking for that functionality.

1 Like