4

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?

Dominique Makowski
  • 1,511
  • 1
  • 13
  • 30
  • Possible duplicate of [Julia function with NULL argument](https://stackoverflow.com/questions/47628523/julia-function-with-null-argument) – Engineero Aug 28 '18 at 14:38

1 Answers1

12

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.

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • dammit ... every time I check this language everything has changed again ... what happened to Nullable?? – Tasos Papastylianou Aug 28 '18 at 18:22
  • 2
    It is moved out to Nullables.jl package. In short: now you have `nothing` that is a singleton instance of `Nothing` and due to Julia 1.0 improvements the recommended style is to use union types like `Union{Int, Nothing}` and then `nothing` indicates absence of the value (and thus sometimes you have to use `Some` type to distinguish between absence of the value and situation where `nothing` is a valid value). – Bogumił Kamiński Aug 28 '18 at 18:35
  • Also worth noting that the code in your solution should be fast due to union splitting optimisation in more recent versions: https://julialang.org/blog/2018/08/union-splitting – Moustache Jun 04 '19 at 08:46