The new
code has a close number of characters to the other code. One problem in both codes however is replicating the word field
or replicating the word this
. This problem can be overcome with Paramters.jl and a twist.
If you define your such such
in functions, then you can have a somewhat elegant code that looks like this:
julia> using Parameters
julia> f1() = 1; f2() = 2;
julia> @with_kw struct MyType
a::Int = f1()
b::Int = f2()
end
MyType
julia> MyType(1, 2)
MyType
a: Int64 1
b: Int64 2
julia> MyType()
MyType
a: Int64 1
b: Int64 2
julia> MyType(a = 1, b = 2)
MyType
a: Int64 1
b: Int64 2
Note that you have access to the keyword constructor and the positional argument constructor. Also the default values are optional.
Given the above keyword constructor you can then define another external constructor that looks more like the function you want:
function MyStruct(some values, etc)
MyStruct(field1 = such such,
field2 = such such,
fieldN = such such)
end
If such such
is small, this will look elegant, otherwise your original attempt will probably be more elegant. Note that you have more flexibility now in wrapping such such
in functions or macros since we are outside the type definition, so you can pass on some values
and etc
to another function to do a computation and come back with the result. Or you can contract some code in such such
in a macro as such:
macro suchsuch1
return esc(quote
such such
such such
end)
end
and the same thing for the macros suchsuch2
and suchsuch3
. Then at call site just use:
function MyStruct(some values, etc)
MyStruct(field1 = @suchsuch1,
field2 = @suchsuch2,
fieldN = @suchsuch3)
end
The macro approach means that you don’t have to pass any arguments.
The same macro approach can be used with the positional argument constructor or perhaps even simpler, straight into your inner constructor. This is probably the solution you were looking for, but since I wrote all the above anyways, I am commenting the whole thing anyways!