Declaring Pair with one fixed type

Let’s say that I’d like to declare a function that takes a Pair as its argument, and that I’d like to restrict the kind of Pair that will be matched. For example:

function foo(p::Pair{String,Any})

do some stuff

end

If I then create a Pair object:

p = “firstkey”=>true

And then call foo(p), I get:
ERROR: MethodError: no method matching foo(::Pair{String,Bool})

Relatedly, I find this confusing:

Tuple{String, Bool} <: Tuple{String, Any}
returns true

but

Pair{String, Bool} <: Pair{String, Any}
returns false.

Pair{String} or Pair{String, <:Any} or Pair{String, T} where T.
Maybe Pair{<:AbstractString, <:Any} is more appropriate, as some string manipulation functions return SubString and you may occasionally use it as the first element of a pair.

Also, read on type parameter invariance and tuple parameter covariance.

6 Likes

Thanks, that’s very helpful, and the suggestion about AbstractString is a good one.