Keyword argument with a default value that depends on a type parameter

Consider the following test function:

julia> test_default(x::T, y::R=Base.rtoldefault(R)) where {R<:Real,T<:Union{R,Complex{R}}} = (R, T)
test_default (generic function with 2 methods)

When a single complex number x is given, this function returns the type R of the real part of x and the complex type T of x:

julia> test_default(1im)
(Int64, Complex{Int64})

julia> test_default(1.0im)
(Float64, Complex{Float64})

However, if we make the second argument y a keyword argument, the function cannot be defined:

julia> test_default_kw(x::T; y::R=Base.rtoldefault(R)) where {R<:Real,T<:Union{R,Complex{R}}} = (R, T)
ERROR: UndefVarError: R not defined

Is this a bug, or there is a reason for this error?

Edit: here is a simpler breaking example:

julia> test_default_kw2(x::T; y::R=0) where {R<:Real,T<:Union{R,Complex{R}}} = (R, T)
ERROR: UndefVarError: R not defined
1 Like

I think the error here is because keyword arguments don’t participate in dispatch nor parameterization; i.e. it doesn’t really make sense to do ; y::R=... because the list of keyword arguments (their names, types, and default values) are static for a given method.

Which leads to the next question of whether it should rather be an error to try and use a type parameter as the type of a keyword argument.

I see. I didn’t know about this. Is this documented somewhere?

There’s one little paragraph in this section: https://docs.julialang.org/en/latest/manual/methods/#Note-on-Optional-and-keyword-Arguments-1, but should probably be featured more prominently here.

1 Like