I am rather new to Julia; my programming is typically in C++, Python, or sometimes Fortran for numerics. My understanding is that Julia lacks something analogous to C++'s private variables (or even Python's "I suggest you treat this as private" convention of using a leading underscore). If I have a container, is there a way to enforce constraints on the objects that I add to the container?
Consider an example: Let's say I want an array of integers, and my constraint is that all integers in the array must share a greatest common factor greater than one. So if I put 12 into the array, any number that's a multiple of 2 or 3 may be added. So I next add 21, and the greatest common factor must now be 3. If I try to add 26, I will get an error because it violates the constraint. But had I added 12 then 26, that would be legal with a greatest common factor of 2.
I realize it's a bit of a contrived example, but it should have all the salient features of what I hope to do, and requires less explanation.
True enforcement is only possible for
immutable
types, where you can check any desired constraints in the inner constructor(s). Outside the type definition there is no way to add new inner constructors, and if there is one you cannot create an instance without going through one.However, while the convention in Python is that fields that begin with
_
are private, the general convention in Julia is that all fields are private (unless they are explicitly documented). It's considered bad style to access fields directly outside the implementation of a type, you should generally have accessor functions instead.