Keyword Arguments

Intermediate Julia

Anthony Markham

Quantitative Developer

Keyword arguments - overview

  • Assigns a keyword to a function parameter.

  • When passing an argument into a function we use the assigned keyword.

  • We can mix keyword arguments with other types, but keyword arguments must come last.

function person(; location)
    return location
end
Intermediate Julia

Keyword arguments - syntax

  • Use the semicolon ; operator to denote keyword arguments.
function person(; location)
    return location
end
person(location="Sydney")
"Sydney"
Intermediate Julia

Keyword arguments - mixing argument types

  • Remember, positional arguments need to be before keyword arguments.
function person(name, ; location)
    return name, location
end
person("Anthony", location="Sydney")
("Anthony", "Sydney")
Intermediate Julia

Variable number of arguments

  • Variable number of arguments (varargs) allows us to pass an arbitrary number of arguments.

  • Use the ellipsis ... operator to mark a parameter as accepting varargs.

function names(name...)
    println(name)
end

names("Anthony", "Ben", "Hannah", "Julia")
("Anthony", "Ben", "Hannah", "Julia")
Intermediate Julia

Variable number of argument types

  • We can mix positional, keyword, and varargs all together in a function definition.
function person(name, education... ; location)
    return name, education, location
end

anthony = person("Anthony", "BE", "BS", "MComm", location="Sydney")
("Anthony", ("BE", "BS", "MComm"), "Sydney")
println(anthony[2][1])
BE
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...