Julia Easy · Lesson 1 · On the house

Methods and specificity

methods(), @which, more-specific wins, ambiguities. Lesson 1 is free — on the house.

Lessons · Julia Easy · Lesson 1 of 10 · On the house

Methods and specificity

methods(), @which, more-specific wins, ambiguities.

Illustration for Julia
Lesson 1 is on the house.

One function name can hold many methods. methods(f) lists them. Each method is a separate definition with its own argument-type signature.

At a call site Julia picks the most specific applicable method. speak(x::Number) is more specific than speak(x::Any) for an Int argument, so the Number method wins.

@which f(args...) shows which method would run for those argument types without guessing. Use it when two methods look close.

If two methods are equally specific and both match, Julia throws a MethodError for ambiguity. Fix it by adding a clearer method (for example specializing both argument types) or by narrowing one signature.

Misses: thinking only the first argument dispatches (that is single dispatch), deleting methods with = reassignment habits from other languages, or ignoring @which when signatures collide.

specificity

speak(x::Any) = "any"
speak(x::Number) = "number"
speak(x::Integer) = "integer"

println(speak("hi"))
println(speak(3.14))
println(speak(7))
println(methods(speak))
Match this when you type.

Quiz

What does methods(speak) show?

Quiz

For speak(7) with Integer <: Number <: Any, which method runs?

Quiz

What does @which f(args...) tell you?

Quiz

What happens when two methods are equally specific and both match?

Check

Match the still for: Methods and specificity.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.