# Union type constructor question

**URL:** <https://discourse.julialang.org/t/union-type-constructor-question/115433>\
**Category:** General Usage\
**Created:** [June 10, 2024, 3:36pm UTC](https://discourse.julialang.org/t/union-type-constructor-question/115433 "2024-06-10T15:36:22Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![slwu89](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/slwu89/32/217323_2.png) [@slwu89](https://discourse.julialang.org/u/slwu89)\
**Post date:** [June 10, 2024, 3:36pm UTC](https://discourse.julialang.org/t/union-type-constructor-question/115433/1 "2024-06-10T15:36:22Z")

</div>

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

```julia
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

```

---

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [June 10, 2024, 3:55pm UTC](https://discourse.julialang.org/t/union-type-constructor-question/115433/2 "2024-06-10T15:55:21Z")

</div>

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
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 `Union`s. Particular `Union`s important enough to get a `const` alias may be an exception, but I don’t have an example off the top of my head.

---

<div class="post-metadata">

**Author:** ![slwu89](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/slwu89/32/217323_2.png) [@slwu89](https://discourse.julialang.org/u/slwu89)\
**Post date:** [June 10, 2024, 4:18pm UTC](https://discourse.julialang.org/t/union-type-constructor-question/115433/3 "2024-06-10T16:18:49Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)\
**Post date:** [June 10, 2024, 4:34pm UTC](https://discourse.julialang.org/t/union-type-constructor-question/115433/4 "2024-06-10T16:34:35Z")

</div>

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