How to specify subtypes of an abstract type as type parameters in Julia?

If I have, say, abstract Componentand require a vector of any of its subtype types, how do I specify a type parameter Vector? This naive fragment does not work:

type Position<:Component
  x::Real
  y::Real
end

v = Vector{Type{Component}}

push!(v, Position)

ERROR: MethodError: `push!` has no method matching push (::Type{Array{Type{Component},1}}, ::Type{Position})
Closest candidates are:
  push!(::Any, ::Any, ::Any)
  push!(::Any, ::Any, ::Any, ::Any...)
  push!(::Array{Any,1}, ::ANY)
+4
source share
2 answers

When you find yourself in a situation where you can use a type, but not any of its subtypes, you can often use it by entering the type parameter in the right place. The following seems to work:

abstract Component

type Position<:Component
  x::Real
  y::Real
end

typealias ComponentType{T<:Component} Type{T}

v = Vector{ComponentType}()

push!(v, Position)

Note that we have created a new type ComponentTypeto which any subtype Component(including Component) belongs , using the type parameter with a construction typealias.

, , , , , v = Vector(); , Julia - .

+3

: , .

Vector{Component}, - :

julia> abstract Foo

julia> v₁ = Foo[]
0-element Array{Foo,1}

julia> vā‚‚ = Vector{Foo}()
0-element Array{Foo,1}

julia> vā‚ƒ = Array(Foo, 0)
0-element Array{Foo,1}

julia> @assert v₁::Vector{Foo} == vā‚‚::Vector{Foo} == vā‚ƒ::Vector{Foo}

:

julia> for T in (:Bar, :Baz, :Qux)
           @eval type $T <: Foo end
       end

julia> bar, baz, qux = Bar(), Baz(), Qux()
(Bar(),Baz(),Qux())

julia> for obj in ans
           push!(v₁, obj)
       end

julia> v₁
3-element Array{Foo,1}:
 Bar()
 Baz()
 Qux()
-1

All Articles