Question about generics and `Base.@kwdef`

Hi all :slight_smile:

What did I do wrong? The following doesn’t work.

Base.@kwdef struct A{T}
    a::T = T()
    function A(a::T) where T
        new{T}(a)
    end
end

struct B end

A{B}()

ERROR: LoadError: MethodError: no method matching A{B}(::B)
Closest candidates are:
  A{T}(; a) where T at C:\Users\<user>\AppData\Local\Programs\Julia-1.7.1\share\julia\base\util.jl:490
Stacktrace:
 [1] A{B}(; a::B)
   @ Main .\util.jl:490
 [2] A{B}()
   @ Main .\util.jl:490
 [3] top-level scope
   @ c:\start.jl:1
in expression starting at c:\start.jl:1

Cheers

You need either two inner constructors (or none)

Base.@kwdef struct A{T}
    a::T = T()
    function A(a::T) where T
        new{T}(a)
    end
    function A{T}(a::T) where T
        new{T}(a)
    end
end

struct B end

@show A{B}()
@show A(B())

because

If any inner constructor method is defined, no default constructor method is provided:

from the documentation.

1 Like