Reputation: 101
I want to have a constructor/method accept an array, but that array can only contain elements of 2 different types. For example:
Array{Union{Int64, String}} = [1, 2, "3"]
But now I want to create the array as [1, 2, "3"]
(not specifying the type) and have it automatically be accepted by the constructor who's expecting arguments of type ::Array{Union{Int64, String}}
.
What happens is that [1, 2, "3"]
is by default of type Any
, and therefore not accepted by my constructor.
Upvotes: 1
Views: 120
Reputation: 7654
You can make an array like that as follows:
julia> Union{Int64, String}[1, 2, "3"]
3-element Array{Union{Int64, String},1}:
1
2
"3"
The documentation for this in the manual can be found here. To quote the manual,
An array with a specific element type can be constructed using the syntax T[A, B, C, ...]. This will construct a 1-d array with element type T, initialized to contain elements A, B, C, etc.
Upvotes: 1