Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 51 / 68

Writing general functions with type parameters

This lesson covers writing general functions with Julia's type parameters, with the aim of producing flexible code that handles several types.

A type parameter (where T) lets you write a function that works for any type rather than fixing one. It is handy when the same logic should serve numbers and strings alike.

In the sample code, the definition function larger(a::T, b::T) where T compares both the numbers in larger(3, 7) and the strings in larger("apple", "banana"). The ::T annotation together with the where T constraint is the idiomatic Julia form.

A common early stumble is how this relates to multiple dispatch. Type parameters are closely bound up with it, and understanding both is important to understanding Julia's type system as a whole.

In professional work, type parameters are used widely as an important way of raising reuse without writing near-identical methods per type.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Julia directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)