Kwargs unexpected (?) error

I ran across the following while writing some code.

function foo( x::Vector, y::Vector; cond=true)

    if cond
        return x .- y
    end
end

function bar(x, y; kwargs...)
    return foo(x, y, kwargs...)
end

# These work fine
foo(rand(10), rand(10))
foo(rand(10), rand(10), cond=true)
bar(rand(10), rand(10))

# This does not
bar(rand(10), rand(10), cond=true)

The error is:

 MethodError: no method matching foo(::Vector{Float64}, ::Vec
tor{Float64}, ::Pair{Symbol, Bool})
The function `foo` exists, but no method is defined for this combin
ation of argument types.

Would someone please explain why this happens here, and what would be the correct way to define the functions above?

Here, you are splatting kwargs as positional arguments. To splat them as keyword arguments, put them after a semicolon: foo(x, y; kwargs...)

In Julia, keyword and positional arguments are completely distinct (unlike e.g. Python).

5 Likes

Makes perfect sense, somehow I missed this detail.

Thanks a lot Steven!

1 Like