Reputation: 525
Say I have a function such as f(x,y)
but the y
parameter is optional. What is the preferred way to set y
as an optional argument? One option that works for me:
function f(x, y=nothing)
# do stuff
if y == nothing
# do stuff
else
# do stuff
end
# do stuff
end
But is this the preferred way? I can't set y
to a single default value to use in calculation, as there are a number of calculations that are done differently when y
is nothing. I could also just have separate functions f(x)
and f(x,y)
but that seems like too much code duplication.
Upvotes: 18
Views: 13625
Reputation: 19132
This is fine. Note that optional arguments cause dispatch. This means that the if y == nothing
(or equivalently, if typeof(y) <: Void
), will actually compile away. You'll get two different functions which depend on whether the user gives a value or not. So in the end, the if
statement compiles away and it's perfectly efficient to do this.
I will note that the same is not currently true for keyword arguments.
Another way to do this is to have two methods:
f(x)
and
f(x,y)
Whether two methods is nicer than 1 method with an if
depends on the problem. Since the if
will compile away using type information, there's no difference between these two approaches other than code organization.
Upvotes: 16