🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Function Arguments

Function arguments are the inputs listed in parentheses when a function is defined. Julia lets an argument carry a default value, be passed by keyword, or name a type it accepts.

A default value fills in a missing argument

The definition gives name a default value. A call can leave it out or pass its own value.

function greet(name="Ana")
    "Hello, " * name
end

println(greet())
println(greet("Ben"))

A keyword argument is passed by name

Keyword arguments sit after a semicolon in the definition. The call names the keyword to change it.

function scale(x; factor=2)
    x * factor
end

println(scale(5))
println(scale(5; factor=3))

An annotation limits the accepted type

Writing ::Int after the argument name limits it to whole numbers. Both calls below pass whole numbers.

function addone(x::Int)
    x + 1
end

println(addone(4))
println(addone(41))

Example

function label(name="Ana"; punct="!")
    "Hello, " * name * punct
end

function shout(word::String)
    uppercase(word)
end

println(label())
println(label("Ben"; punct="."))
println(shout("hey"))

Key points

  • Default value: the value used when the caller leaves that argument out.
  • Positional argument: a value passed by its position, before any semicolon.
  • Keyword argument: a value passed by name, listed after a semicolon.
  • Keyword in a definition: keyword arguments are written after a semicolon in the argument list.
  • Type annotation: ::Int after an argument name limits that argument to whole numbers.
  • Accepted values: an annotated argument only accepts values of the named type.

In this example, label has a default name and a keyword argument for the punctuation. The first call uses both defaults, and the second call changes the keyword by name. Last, shout annotates its argument as a String and returns it in uppercase.

Note

A later lesson shows how several methods can share one name, one for each type.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

Which call passes a keyword argument to scale(x; factor=2)?