🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Parametric Methods

A parametric method is a method that works for a type chosen at call time. The type letter stands for any one type in that call.

One method can report the type it was given

The letter T stands for the type of the argument. Each call prints that type.

showtype(x::T) where T = T
println(showtype(5))
println(showtype("hi"))

One method can require matching argument types

Both argument spots use the same letter T. Both calls use matching argument types.

pair(x::T, y::T) where T = "same type"
println(pair(1, 2))
println(pair("a", "b"))

A mixed pair has no matching method

A mixed pair has no matching method. A try block catches the error and prints a fixed message.

pair(x::T, y::T) where T = "same type"
try
    pair(1, "a")
catch e
    println("types must match")
end

Example

add(x::T, y::T) where T = x + y
println(add(2, 3))
println(add(2.5, 1.5))
try
    add(2, "a")
catch e
    println("types must match")
end

Key points

  • Type variable: a letter like T stands for one type in a single call.
  • Where clause: the words where T after a method name introduce T for that method.
  • Same type rule: the same type letter in two argument spots forces both arguments to share one type.
  • Different types: a mixed pair has no matching method and the call fails.
  • One method, many types: the same method can serve whole numbers, decimals, and text.

In this example, one method adds two values of one shared type. Two matching calls print their sums. A mixed call fails, and a try block prints a fixed message.

Note

T is only a name inside its own method.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

pair takes two arguments of one shared type. Which call matches pair?