print and println@printftry-catch for Exception HandlingfinallyOften, when you define a function, some of its parameters will have typical or common values. Requiring the caller to provide these common values every time can make function calls verbose and repetitive. Julia allows you to assign default values to function arguments, making your functions more flexible and easier to use. If a caller omits an argument that has a default value, Julia automatically uses that default. If the caller provides a value, it overrides the default.
You specify a default value for an argument using the assignment operator = directly in the function's signature. The default value can be any valid Julia expression, from a simple number to a more complex object or even a call to another function (though the latter is evaluated when the function is defined, not when it's called, for default values themselves).
Let's look at a simple example. Suppose we want a function to greet a person, but most of the time, the greeting is "Hello".
function greet(name, greeting="Hello")
println("$greeting, $name!")
end
Now, you can call this function in two ways:
greet("Alice") # Uses the default greeting
greet("Bob", "Hi") # Provides a specific greeting
This would produce the output:
Hello, Alice!
Hi, Bob!
As you can see, greet("Alice") automatically used "Hello" because we didn't supply a second argument. In the call greet("Bob", "Hi"), our provided string "Hi" was used instead of the default.
A function can have multiple arguments with default values. When calling such a function with positional arguments, the values you provide fill the arguments from left to right.
Consider a function to set up a user profile:
function setup_profile(username, followers=0, theme="light")
println("Profile for $username: $followers followers, using $theme theme.")
end
setup_profile("developer123")
setup_profile("designer_jane", 150)
setup_profile("julia_guru", 10000, "dark")
The output demonstrates how the defaults are applied:
Profile for developer123: 0 followers, using light theme.
Profile for designer_jane: 150 followers, using light theme.
Profile for julia_guru: 10000 followers, using dark theme.
In the first call, both followers and theme use their defaults. In the second call, followers is specified as 150, but theme still uses its default "light". The third call specifies all arguments.
When defining a function with positional arguments, any arguments that have default values must be listed after all arguments that do not have default values. This rule is important because Julia needs to determine unambiguously which argument corresponds to which value when the function is called.
For example, this is a correct definition:
function calculate_payment(amount, currency="USD")
println("Payment: $amount $currency")
end
However, if you try to define a function with a required argument after an optional one, like this:
# This definition will cause an error:
# function неправильный_порядок(порт=8080, имя_сервера) # Incorrect order: port=8080, server_name
# println("Настройка $имя_сервера на порту $порт...")
# end
Julia will report an error (e.g., ERROR: syntax: non-default argument server_name after default argument) because it wouldn't know how to interpret a single argument call like неправильный_порядок("my_server"). Is "my_server" meant for порт or имя_сервера? To avoid this ambiguity, required positional arguments always come first.
Default values are particularly effective when used with keyword arguments. As you may recall, keyword arguments are specified by name when calling a function, so their order doesn't matter. This makes it very convenient to override only specific defaults, regardless of their position in the function definition.
Keyword arguments are defined after a semicolon ; in the function signature.
function configure_service(; service_name="DefaultService", port=80, timeout=5000)
println("Configuring $service_name on port $port. Timeout: $timeout ms.")
end
# Calling with keyword arguments
configure_service()
configure_service(service_name="DataProcessor")
configure_service(port=8080, timeout=10000)
configure_service(timeout=2000, service_name="AuthService", port=443)
Output:
Configuring DefaultService on port 80. Timeout: 5000 ms.
Configuring DataProcessor on port 80. Timeout: 5000 ms.
Configuring DefaultService on port 8080. Timeout: 10000 ms.
Configuring AuthService on port 443. Timeout: 2000 ms.
Notice how easy it is to initialize timeout or port without having to specify other arguments if their defaults are acceptable.
Employing default values for function arguments offers several advantages:
process_data(data) and later change it to process_data(data; strict_mode=false), existing calls to process_data(my_data) will continue to work, with strict_mode defaulting to false.Default arguments are widely used in Julia for situations like:
# Plotting function
# function create_plot(x, y; color="blue", linewidth=1, title="")
# # ... plotting logic ...
# end
# function connect_database(host="localhost", port=5432; user="guest", password="")
# # ... connection logic ...
# end
# function solve_equation(coeffs; initial_guess=0.0, tolerance=1e-6, max_iterations=100)
# # ... solving logic ...
# end
By allowing certain arguments to have default values, you empower users of your functions to interact with them more efficiently, providing only the information that deviates from the standard or expected behavior. This is a common practice that leads to cleaner, more maintainable, and user-friendly Julia code.
Was this section helpful?
© 2026 ApX Machine LearningEngineered with