I’ve been using Julia nearly daily for about a year and thought I was fluent in the basics by now. Here’s an example that proves I was mistaken.
(I believe that) The syntax T[]
defines an array literal and casts the elements to type T
. For example:
julia> Float64[1,2,3]
3-element Array{Float64,1}:
1.0
2.0
3.0
Similarly, (I believe that) Any[]
is useful for initializing an array with elements of type Any
, so that it can hold elements of other types later.
julia> Any[1,2,3]
3-element Array{Any,1}:
1
2
3
So far so good. Now let’s do the same thing on a more complex array:
julia> x = Any[ [1,2,3], ["1","2","3"], [1.0,2.0,3.0] ]
3-element Array{Any,1}:
[1, 2, 3]
String["1", "2", "3"]
[1.0, 2.0, 3.0]
julia> typeof.(x)
3-element Array{DataType,1}:
Array{Int64,1}
Array{String,1}
Array{Float64,1}
Instead of casting the elements of x
to Any, it seems to have done the complete opposite and made the types more specific. On a heterogeneous array, I would have expected Any[]
to produce output similar to what you get if you leave out the Any
specification, like this:
julia> y = [ [1,2,3], ["1","2","3"], [1.0,2.0,3.0] ]
3-element Array{Array{Any,1},1}:
Any[1, 2, 3]
Any["1", "2", "3"]
Any[1.0, 2.0, 3.0]
What in the world is going on here? What is this called, and where is it documented? (Googling “Julia Any” isn’t very helpful …)