Skip to content

Commit f9cde29

Browse files
jamesonquinnantoine-levitt
authored andcommitted
docs: add FAQ on parametric invariance (JuliaLang#21261)
1 parent bf34fab commit f9cde29

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

doc/src/manual/faq.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,32 @@ julia> remotecall_fetch(anon_bar, 2)
741741
1
742742
```
743743

744+
## Troubleshooting "method not matched": parametric type invariance and `MethodError`s
745+
746+
### Why doesn't it work to declare `foo(bar::Vector{Real}) = 42` and then call `foo([1])`?
747+
748+
As you'll see if you try this, the result is a `MethodError`:
749+
750+
```jldoctest
751+
julia> foo(x::Vector{Real}) = 42
752+
foo (generic function with 1 method)
753+
754+
julia> foo([1])
755+
ERROR: MethodError: no method matching foo(::Vector{Int64})
756+
Closest candidates are:
757+
foo(!Matched::Vector{Real}) at none:1
758+
```
759+
760+
This is because `Vector{Real}` is not a supertype of `Vector{Int}`! You can solve this problem with something
761+
like `foo(bar::Vector{T}) where {T<:Real}` (or the short form `foo(bar::Vector{<:Real})` if the static parameter `T`
762+
is not needed in the body of the function). The `T` is a wild card: you first specify that it must be a
763+
subtype of Real, then specify the function takes a Vector of with elements of that type.
764+
765+
This same issue goes for any composite type `Comp`, not just `Vector`. If `Comp` has a parameter declared of
766+
type `Y`, then another type `Comp2` with a parameter of type `X<:Y` is not a subtype of `Comp`. This is
767+
type-invariance (by contrast, Tuple is type-covariant in its parameters). See [Parametric Composite
768+
Types](@ref man-parametric-composite-types) for more explanation of these.
769+
744770
### Why does Julia use `*` for string concatenation? Why not `+` or something else?
745771

746772
The [main argument](@ref man-concatenation) against `+` is that string concatenation is not

0 commit comments

Comments
 (0)