Roger-luo / Configurations.jl

Options & Configurations made easy.
https://configurations.rogerluo.dev/stable
MIT License
80 stars 12 forks source link

Auto-conversion doesn't work for Unitful types when using keyword arguments #33

Closed chenspc closed 3 years ago

chenspc commented 3 years ago

The Unitful.jl documentation recommends using concrete types within struct definitions. However, if using keyword arguments to create an option type object, the auto-conversion doesn't happen.

Similar usage with Base.@kwdef seems to work fine, but of course without all the nice features that come with the @option types...

julia> using Unitful, Configurations

julia> @option struct TT
           a::typeof(1.0u"m")
           b::Unitful.Length
       end

julia> t1 = TT(2.0u"m", 3.0u"nm")
TT(;
    a = 2.0 m,
    b = 3.0 nm,
)

julia> t2 = TT(2u"m", 3u"nm")
TT(;
    a = 2.0 m,
    b = 3 nm,
)

julia> t3 = TT(;a=2.0u"m", b=3.0u"nm")
TT(;
    a = 2.0 m,
    b = 3.0 nm,
)

julia> t4 = TT(;a=2u"m", b=3u"nm")
ERROR: TypeError: in keyword argument a, expected Quantity{Float64, š‹, Unitful.FreeUnits{(m,), š‹, nothing}}, got a value of type Quantity{Int64, š‹, Unitful.FreeUnits{(m,), š‹, nothing}}
Stacktrace:
 [1] top-level scope
   @ REPL[6]:1

julia> t5 = TT(;a=2.0u"m", b=3u"nm")
TT(;
    a = 2.0 m,
    b = 3 nm,
)

julia> t6 = TT(;a=2.0u"nm", b=3u"nm")
ERROR: TypeError: in keyword argument a, expected Quantity{Float64, š‹, Unitful.FreeUnits{(m,), š‹, nothing}}, got a value of type Quantity{Float64, š‹, Unitful.FreeUnits{(nm,), š‹, nothing}}
Stacktrace:
 [1] top-level scope
   @ REPL[8]:1

julia> Base.@kwdef struct KT
           a::typeof(1.0u"m")
           b::Unitful.Length
       end
KT

julia> k1 = KT(2.0u"m", 3.0u"nm")
KT(2.0 m, 3.0 nm)

julia> k2 = KT(2u"m", 3u"nm")
KT(2.0 m, 3 nm)

julia> k3 = KT(;a=2.0u"m", b=3.0u"nm")
KT(2.0 m, 3.0 nm)

julia> k4 = KT(;a=2u"m", b=3u"nm")
KT(2.0 m, 3 nm)

julia> k5 = KT(;a=2.0u"m", b=3u"nm")
KT(2.0 m, 3 nm)

julia> k6 = KT(;a=2u"nm", b=3u"nm")
KT(2.0e-9 m, 3 nm)
Roger-luo commented 3 years ago

thanks for reporting, this is a bug.

Roger-luo commented 3 years ago

should be fixed now.

chenspc commented 3 years ago

Thanks a lot for fixing this so quickly!