File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -741,6 +741,32 @@ julia> remotecall_fetch(anon_bar, 2)
741
741
1
742
742
```
743
743
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
+
744
770
### Why does Julia use ` * ` for string concatenation? Why not ` + ` or something else?
745
771
746
772
The [ main argument] (@ref man-concatenation) against ` + ` is that string concatenation is not
You can’t perform that action at this time.
0 commit comments