Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Inner Constructor Methods in Julia?

Tags:

julia

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?

like image 945
logankilpatrick Avatar asked Oct 22 '25 19:10

logankilpatrick


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)
like image 171
Przemyslaw Szufel Avatar answered Oct 25 '25 02:10

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!