Struct with Parameters.jl and outer function

Hi everyone,

I have a simple idea: I want to create a Grid object containing the parameters of my model. I want the user to give values using Unitful to have units and to internally have consistent values without the units. I have managed to do what I want like this for example:

using Unitful

struct Grid
    nx::Int
    Lx::Float64
    Δx::Float64
    x::StepRangeLen

    function Grid(nx, Lx)
        Δx = Lx / (nx-1)
        x = range(0, length=nx, stop= Lx)
        new(nx, Lx, Δx, x)
    end
end

# convert Lenght unit
function Grid(nx::Int, Lx::Unitful.Length)
    Grid(nx, ustrip(u"m", Lx))
end

grid = Grid(101, 1000u"1000")

I am trying to do the same thing using Parameters.jl (to understand it and to see if it can simplify a bit the writing) and I didn’t manage to make it work. Here is my try:

using Unitful
using Parameters

@with_kw struct Grid
    nx::Int
    Lx::Float64
    Δx::Float64 = Lx / (nx-1)
    x::StepRangeLen = range(0, length=nx, stop= Lx)
end

# convert Lenght unit
function Grid(nx::Int, Lx::Unitful.Length)
    Grid(nx, ustrip(u"m", Lx))
end

grid = Grid(101, 1000u"1000")

which yield ERROR: MethodError: no method matching Grid(::Int64, ::Int64)

Is what I am trying to do not possible?

The following example

using Unitful
using Parameters

@with_kw struct Grid
    nx::Int
    Lx::Float64
    Δx::Float64 = Lx / (nx-1)
    x::StepRangeLen = range(0, length=nx, stop= Lx)
end

# convert Length unit
function Grid(nx::Int, Lx::Unitful.Length)
    Grid(;nx=nx, Lx=ustrip(u"m", Lx))
end

@show Grid(101, 1000u"m")
@show Grid(101, 1000u"1000")

yields

Grid(101, 1000 * u"m") = Grid
  nx: Int64 101
  Lx: Float64 1000.0
  Δx: Float64 10.0
  x: StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}

ERROR: MethodError: no method matching Grid(::Int64, ::Int64)

which seems sensible to me. Your first example seems to break units, because you manage to construct a Grid from a non-length unit?

Thx for your reply. I think I did a small mistake when I copy-pasted my code because what I wanted to do first was:

 Grid(101, 1000u"m")

and not

 Grid(101, 1000u"1000")

My mistake in the code was to not write the name of the variables for the input as you should do when using Parameters.jl.

Thx for your help!