Problem with optional argument with default value of missing

I have a small package CurrentPopulationSurvey.jl that I’m working on and in it I have the following function defined:

function cpsdata(year::Int, month::Int, vars::Vector{String}=missing)
    data = readdlm(project_path("data/links_dicts.csv"), ',', skipstart=1)
    registerdep(year, month, data)
    return createtable(year, month, vars, data)
end

When I load the package and call cpsdata without the optional argument I get a MethodError:

julia> cpsdata(2020,1)
ERROR: MethodError: no method matching cpsdata(::Int64, ::Int64, ::Missing)
Closest candidates are:
  cpsdata(::Int64, ::Int64, ::Array{String,1}) at C:\Users\mthel\.julia\packages\CurrentPopulationSurvey\PgkXT\src\CurrentPopulationSurvey.jl:74
  cpsdata(::Int64, ::Int64) at C:\Users\mthel\.julia\packages\CurrentPopulationSurvey\PgkXT\src\CurrentPopulationSurvey.jl:74
Stacktrace:
 [1] cpsdata(::Int64, ::Int64) at C:\Users\mthel\.julia\packages\CurrentPopulationSurvey\PgkXT\src\CurrentPopulationSurvey.jl:75
 [2] top-level scope at REPL[25]:1

But the method clearly exists:

julia> methods(cpsdata)
# 2 methods for generic function "cpsdata":
[1] cpsdata(year::Int64, month::Int64, vars::Array{String,1}) in CurrentPopulationSurvey at C:\Users\mthel\.julia\packages\CurrentPopulationSurvey\PgkXT\src\CurrentPopulationSurvey.jl:74
[2] cpsdata(year::Int64, month::Int64) in CurrentPopulationSurvey at C:\Users\mthel\.julia\packages\CurrentPopulationSurvey\PgkXT\src\CurrentPopulationSurvey.jl:74

I don’t understand why the second method isn’t being dispatched…? This, for example, works fine:

function foo(a,b,c=missing)
    return ismissing(c) ? a + b : a + b + c
end

julia> foo(1,2)
3

julia> foo(1,2,3)
6

julia> foo(1,2,missing)
3

Have you tried vars::Union{Vector{String}, Missing}? missing is a value of type Missing, and will not match the expected Vector{String}.

Your foo example works because the type of c is unspecified, and automatically accommodates Missing.

Also, you may not need to specify Int, which could potentially limit the function’s composability with other packages.

2 Likes

I’m very embarrassed to not have realized that…been staring at the computer too long. Thanks : )