3
votes

I have a function f(x). I would like that function to have an optional parameter of type vector. For instance, f(x; y::Vector=[1,2,3]). However, I'd like the default value to be something else (null? missing? void?) so that I can easily catch it and react to it.

In R, I would say function(x, y=NULL){} and then if(is.null(y)){whatever}.

What would be the most julian way of doing something similar?

1

1 Answers

10
votes

The pattern referenced in the comment by Engineero is cleanest, but it assumes a positional argument. If you insist on having a keyword argument (as you do in your question) to your function use:

function f(x; y::Union{Vector, Nothing}=nothing)
    if y === nothing
        # do something
    else
        # do something else
    end
end

This is usually needed only if you have a lot of keyword arguments, as otherwise I would recommend defining methods with different positional parameter signatures.

Of course it is fully OK to use this pattern with nothing also for positional arguments if you find it preferable.