🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Where Constraints

A where constraint is a limit on a type variable that says which types it may stand for. It keeps a method open only to the types it can handle.

A constraint limits a method to numbers

The method adds 1 to a number. It works for integers and decimals.

f(x::T) where T <: Number = x + 1
println(f(5))
println(f(2.5))

One variable forces one shared type

Both arguments share one type. The sum of 3 and 4 is 7, and the sum of 1.5 and 2.5 is 4.0.

f(x::T, y::T) where T <: Number = x + y
println(f(3, 4))
println(f(1.5, 2.5))

Integer is under Number, text is not

Int64 sits under Number. String does not sit under Number.

println(Int64 <: Number)
println(String <: Number)

Example

double(x::T) where T <: Number = 2 * x
println(double(4))
println(double(2.5))
println(typeof(double(4)))

Key points

  • Type variable: a type variable is a placeholder that stands for one type in a method.
  • Where clause: a where clause introduces a type variable for one method.
  • Constraint: a constraint limits which types the variable may stand for.
  • Number limit: T <: Number lets T stand for integer and decimal types.
  • Shared type: two arguments with the same variable must share one type.

In this example, double takes any number type. Doubling 4 gives 8, doubling 2.5 gives 5.0, and the doubled integer keeps the type Int64.

Note

the constraint sits after the method name, in the where clause.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does T <: Number allow T to stand for?