Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to type function kwargs in Julia?

The following works for standard Varargs.

function int_args(args::Integer...)
    args
end

int_args(1, 2, 3)
# (1, 2, 3)

int_args(1, 2, 3.0)
# ERROR: MethodError: `int_args` has no method matching int_args(::Int64, ::Int64, ::Float64)

However, when applying this same syntax to kwargs, all function calls seem to error.

function int_kwargs(; kwargs::Integer...)
    kwargs
end

int_kwargs(x=1, y=2)
# ERROR: MethodError: `__int_kwargs#0__` has no method matching __int_kwargs#0__(::Array{Any,1})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
679 views
Welcome To Ask or Share your Answers For Others

1 Answer

Normal keyword arguments can have types, as in function f(x; a::Int=0), but this doesn't work for "rest" keyword arguments. Also note that since we currently don't dispatch on keyword arguments, the a::Int in this case is a type assertion and not a dispatch specification.

It looks like this case is not handled well, and needs a better error message at least. I'd encourage you to file an issue at https://github.com/JuliaLang/julia/issues.

I'm not sure what the syntax x::T... should mean for keyword arguments. In the case of varargs, it's clear that each element of x should have type T, but for rest keyword arguments each element is actually a symbol-value pair. Of course we could give it the meaning you describe (all values have type T), but this doesn't seem to come up very often. Keyword arguments tend to be quite heterogeneous, unlike varargs which are more like lists or arrays.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...