Simplifying code with the @kwdef macro

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.

As of Julia version 1.3, the @kwdef macro is not exported. There is a feature request to export it. Should you feel uncomfortable using non-exported features, consider using the Parameters.jl package instead.

Next, we will discuss code generation pattern, which allows us to create new functions dynamically so as to avoid writing repeated boilerplate code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.137.17