Keyword arguments
Keyword arguments are another type of argument that can be passed to a function. A keyword argument is similar in concept to the NamedTuple that we saw in the previous chapter - it gives us a name to assign to a value, which gives us a good understanding of what that value actually represents.
To declare a keyword argument, we use a semicolon ;
in the function declaration to denote a keyword argument.
function my_func(; my_arg)
return my_arg
end
When actually calling the function, the semicolon is not required.
my_func(; my_arg=1)
Keep in mind that while you can mix both positional and keyword arguments in the same function, keyword arguments must always come after positional arguments in a function declaration.
This exercise is part of the course
Intermediate Julia
Exercise instructions
- Re-write the
my_profit
function to use keyword arguments. - Call
my_profit
but flip the order of the arguments, passingcurrent_price=100.0
first, followed byprevious_price=105.0
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define my_profit with keyword arguments and a default argument
function my_profit(____previous_price::Float64, current_price::Float64, fees::Int64=2)
return current_price - previous_price - fees
end
# Call my_profit
my_profit(____, ____)