Way to check if variable is of type Union?

Pretty abstract question that I can’t really wrap my head around.

What is a robust way of checking if something is a Union?


For example, (from the docs)

> typeof(Union{Real,String})
Union
> typeof(Union{AbstractFloat})
DataType

The use case for this is calling subtype and supertype

So first question, can you just flat-out find out if something is a Union?

And a follow-up, is there a way to broadcast sub/super-type over all the params that appear within a Union?

(i.e. Real and String for the first union above, AbstractFloat for the second)

Values always have concrete types (by definition)—an object cannot have an abstract type (and in particular it cannot have a union type). A variable could be inferred to have a union type, but that’s just an implementation detail of the optimizer. Locations like fields in structures or slots in arrays can be abstractly typed, and that can be queried with fieldtype and eltype like so:

julia> fieldtype(typeof(1//2), :num)
Int64

julia> eltype(rand(5))
Float64
3 Likes

typeof. The case above is simply because Union{} of a single type is always that type itself.

Well, the second one isn’t a union.

tx = Union{Int64, Float64};
fx(::Int64) = print("Int");
fx(::Float64) = print("Float");
tarr = Array{tx}(undef, 10) ## 
tarr[1:2:end] .= 1.0;
tarr[2:2:end] .= 1; #  
fx.(tarr)
FloatIntFloatIntFloatIntFloatIntFloatInt