Ferenc
Ferenc

Reputation: 874

How to use inheritance in a more complex type in Julia

I am trying to use a general type Any in the following function:

function f(arr::Array{Tuple{ASCIIString, Any},1})
    arr[1]
end

and it works in

f([("a",1), ("b","x")])

but in

f([("a",1)])

it does not work. One'd think an Int is actually an Any, but apparently not.

How to get f working in this latter case? I am interested in a general solution because this problem crops up in many places in Julia and the above is just a simple example. Should I use a Union of all types in place of Any in the tuple?

Upvotes: 3

Views: 405

Answers (1)

Toivo Henningsson
Toivo Henningsson

Reputation: 2699

Type parameters in Julia are invariant, see http://julia.readthedocs.org/en/latest/manual/types/#parametric-composite-types. To get the behavior that you are after, you need to parameterise your function by a type parameter:

function f{T <: Tuple{ASCIIString, Any}}(arr::Array{T,1})
    arr[1]
end

Upvotes: 7

Related Questions