Weird error with optional arguments

I am pretty new to julia - and I encountered this error when I was trying to implement a code that takes an optional argument that is a dict.

So I try

function test_optional(x,y,z=nothing)
   print("$x,$y")
    if z!=nothing
        print(z)
    end
end

which gives the expected output

test_optional (generic function with 2 methods)

And it works fine. Now if I add a type to z such as Vector ,

function test_optional_vector(x,y,z::Vector{Float64}=nothing)
   print("$x,$y")
    if z!=nothing
        print(z)
    end
end

Again this leads to a function with 2 methods, however when I try to run this without z

test_optional_vector(1,2)

I get this error,

MethodError: no method matching test_optional_vector(::Int64, ::Int64, ::Nothing)
Closest candidates are:
  test_optional_vector(::Any, ::Any) at In[32]:1
  test_optional_vector(::Any, ::Any, !Matched::Array{Float64,1}) at In[32]:1

Stacktrace:
 [1] test_optional_vector(::Int64, ::Int64) at ./In[32]:2
 [2] top-level scope at In[33]:1
 [3] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091

Any idea what is going on? This is with Julia 1.5

The variable z is not allowed to be nothing due to the type declaration.
test_optional_vector(x,y,z::Union{Vector{Float64}, Nothing}=nothing) should work.

1 Like

Is there a shorter way to pass typed optional arguments?

Thanks!

You could use multiple dispatch to manually define 2 methods, one with and one without the parameter. This way, you don’t need the sentinel value nothing.
This is not a 1:1 correspondence, but usually the more “Julian” way.

2 Likes

Thanks!
That would have been my next step
Subramanya

In your example, this could be

test_optional_vector(x,y) = print("$x,$y")
function test_optional_vector(x,y,z::Vector{Float64})
   test_optional_vector(x,y)
   print(z)
end
2 Likes