Iterating through types of a Union in a type-stable manner


I have the following:

union_types(x::Union) = union_types(x.a, x.b)
union_types(a::Union, b::Type) = (union_types(a)..., b)
union_types(a::Type, b::Type) = (a, b)
union_types(x::Type) = (x,)
# For completeness
union_types(a::Type, b::Union) = (a, union_types(b)...)

which is a way to get the types composing a Union as a Tuple. However, it is not type-stable:


Is it possible to get, or iterate over, the Types composed in a Union in a type-stable manner, without knowing beforehand how many types will be? The user provide us with a Union of types, so we cannot make assumptions on the total number of types beforehand.

1 Like

Take a look at this thread and other threads that are referenced in it: Macro to write function with many conditionals

There is no simple answer, although there are many possibilities.

I think you should try to find another API that doesn’t require you to use internals like this. Manipulating types like this is not really how the language is supposed to be used and you will always have pushbacks from various parts if you go this way.