NamedTuple with explicit (abstract) types

How can I create a NamedTuple with an abstract type?

When I try the following code, nt.a is of concrete type Vector{Float64} and the assignment nt.a[] = arr fails because a Matrix{Int64} cannot be converted to a Vector{Float64}.

arr = zeros(Int, 2, 3)

nt = (a = Ref(Array{Float64, 1}()), b = 3) # I'd like to store AbstractArray instead of Vector{Float64}
nt.a[] = arr # MethodError: no method matching Vector{Float64}(::Matrix{Int64})
nt.a[][2, 2] = 100

arr[2, 2] == 100

Just specify a looser type parameter (don’t worry about the NamedTuple part, also)

julia> x = Ref{AbstractArray}();

julia> x
Base.RefValue{AbstractArray}(#undef)

julia> x[] = [1];

julia> x[] = [1 2];
2 Likes

Thanks a lot!

I require the named tuple anyways, as I bundle some of those arrays.

julia> x = @NamedTuple{a::Integer, b::AbstractArray}((3, [4,5]))
NamedTuple{(:a, :b), Tuple{Integer, AbstractArray}}((3, [4, 5]))
2 Likes