Search code examples
functionnullargumentsjuliadefault

Julia: function with optional argument of type Vector but default to null?


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?


Solution

  • 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.