# How to automatically "transfer" keyword arguments from a component structure to the constructor of the wrapping object?

**URL:** <https://discourse.julialang.org/t/how-to-automatically-transfer-keyword-arguments-from-a-component-structure-to-the-constructor-of-the-wrapping-object/83737>\
**Category:** General Usage\
**Created:** [July 4, 2022, 9:37am UTC](https://discourse.julialang.org/t/how-to-automatically-transfer-keyword-arguments-from-a-component-structure-to-the-constructor-of-the-wrapping-object/83737 "2022-07-04T09:37:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sylvaticus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sylvaticus/32/203883_2.png) [@sylvaticus](https://discourse.julialang.org/u/sylvaticus)\
**Post date:** [July 4, 2022, 9:37am UTC](https://discourse.julialang.org/t/how-to-automatically-transfer-keyword-arguments-from-a-component-structure-to-the-constructor-of-the-wrapping-object/83737/1 "2022-07-04T09:37:25Z")

</div>

I have a struct (let’s say `Model`) where I would like to logically divide the fields in two different objects (lets’s say `optionsa` and `optionsb`) but I want to keep this division transparent to the user so that it can just call the main structure using keyword arguments of the two wrapped structures. Of course, I could write a custom constructor with all the fields of the wrapped structs, but I wonder if there is a way to do it automatically.

For example:

```julia
Base.@kwdef mutable struct OptionsA
    option1a::Int64 = 0
    option2a::String = "foo"
end
Base.@kwdef mutable struct OptionsB
    option1b::Int64 = 1
    option2b::String = "boo"
end

mutable struct Model
    optionsa::OptionsA 
    optionsb::OptionsB 
    otherstuff
end

# User should be able to do any of the following:
Model()
Model(option1a=1)
Model(option1a=1,option2b="zzz")
...

```

---

<div class="post-metadata">

**Author:** ![sylvaticus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sylvaticus/32/203883_2.png) [@sylvaticus](https://discourse.julialang.org/u/sylvaticus)\
**Post date:** [July 4, 2022, 10:14am UTC](https://discourse.julialang.org/t/how-to-automatically-transfer-keyword-arguments-from-a-component-structure-to-the-constructor-of-the-wrapping-object/83737/2 "2022-07-04T10:14:11Z")

</div>

This seems to work:

```julia
function Model(;kwargs...)
    m = Model(OptionsA(),OptionsB(),nothing)
    thisobjfields = fieldnames(typeof(m))
    for (kw,kwv) in kwargs
       for f in thisobjfields
          fobj = getproperty(m,f)
          if kw in fieldnames(typeof(fobj))
              setproperty!(fobj,kw,kwv)
          end
        end
    end
    return m
end

```
