Why use Inner Constructor Methods in Julia?

Viewed 231

If I am understanding the docs correctly, the value of Inner Constructor Methods is that I can use them as a regular constructor but with some additional changes to the values?

For example, using a normal constructor it is not possible to take the constructor arguments and add the number 1 to them but with an Inner Constructor, this is possible?

1 Answers

Inner constructor allows you to replace the default constructor. For example:

julia> struct A
       x::Int
       A(a::Int,b::Int)=new(a+b)
       end

julia> A(3)
ERROR: MethodError: no method matching A(::Int64)

julia> A(3,5)
A(8)

Note that when the inner constructor is not defined, it actually exists with the default parameter set. However adding the external constructor(s) will not override the behavior of the internal one:

julia> struct B
       x::Int
       end

julia> B(a::Int,b::Int)=B(a+b);

julia> B(3)
B(3)

julia> B(3,5)
B(8)
Related