Given that the keyword definition pattern addresses a fairly common use case, there is already a macro provided by Julia to help define structs along with constructors accepting keyword arguments. The macro is currently not exported, but you can use it directly as follows:
Base.@kwdef struct TextStyle
font_family
font_size
font_weight = "Normal"
foreground_color = "black"
background_color= "white"
alignment = "center"
rotation = 0
end
Basically, we can just place the Base.@kwdef macro in front of the type definition. As a part of the type definition, we can also provide default values. The macro automatically defines the struct and the corresponding constructor function with keyword arguments. We can see that by using the methods function as follows:
From the output, we can see that the first method is the one that accepts keyword arguments. The second method is the default construct that requires positional arguments. Now, creating new objects is as convenient as we would like:
We should note that the preceding definition did not specify any default values for font_family and font_size. So, those fields are mandatory when creating a TextStyle object:
Using this macro can greatly simplify object construction and make the code more readable. There is no reason not to use it everywhere.
Next, we will discuss code generation pattern, which allows us to create new functions dynamically so as to avoid writing repeated boilerplate code.