How to remove Nothing from an array eltype when there are no nothing in the array?

Viewed 147

For instance, if the output of a function (e.g. indexin) has the Vector{Union{Nothing, Int64}} type,
but it is known in advance that only values will be output (no nothing).
And this output should be fed to another function
which is buggy for such a type, but fine with an array of simple Int64.

Say

julia> output = Union{Nothing, Int64}[1, 2]  # in practice, that would be output from a function
2-element Vector{Union{Nothing, Int64}}:
 1
 2

How to convert that output to an array of Int64 ?

The following works in this case, and could be gathered in a function, but there must be a more elegant way.

julia> subtypes = Base.uniontypes(eltype(output))
2-element Vector{Any}:
 Nothing
 Int64

julia> no_Nothing = filter(!=(Nothing), subtypes)
1-element Vector{Any}:
 Int64

julia> new_eltype = Union{no_Nothing...}
Int64

julia> Array{new_eltype}(output)
2-element Vector{Int64}:
 1
 2

1 Answers

Try something:

julia> output = Union{Nothing, Int64}[1, 2]
2-element Vector{Union{Nothing, Int64}}:
 1
 2

julia> something.(output)
2-element Vector{Int64}:
 1
 2
Related