Automatic keyword argument constructor

Is there a way to have Julia automatically defining a constructor using keywords arguments?

# the composite type
struct Person
  name::String
  age::Int
end
# generates automatically this constructor:
me = Person("Hugo", 24)
# is there a way to define automatically
# this constructor using only keyword arguments
# corresponding to fields names?
me = Person(;name="Hugo", age=24)

I think this could be achieved using macros, but I’m not good at it and do not know how to do. Now, I’m forced to implement it manually:

struct Person
  name::String
  age::Int
  Person(;name::String,age::Int) = new(name,age)
end

It’s a bit cumbersome.

I believe Parameters.jl is exactly what you’re looking for

3 Likes

Thanks, it does the trick!

import Parameters.with_kw

@with_kw struct Person
   name::String
   age::Int
end

julia> Person(name="Hugo", age=24)
Person
  name: String "Hugo"
  age: Int64 24

note: it also changes the way the structure prints itself, without Parameters.jl, it was

julia> Person(name="Hugo", age=24)
Person("Hugo", 24)

There’s also Base.@kwdef. It’s very poorly advertised, though. It should probably be mentioned in the Constructors chapter in the manual.

5 Likes

perhaps Base.@kwdef is not documented because it is not exported, is hence considered an internal function, and might be removed in future? seems very useful though. definitely a keeper!

Parameters.jl also export @unpack, which is very useful.

1 Like