Private Properties in Julia 0.7

Can create private properties by defining:

struct MyType
    a
    b
end

function getpublicproperties(x::MyType, field::Symbol)
    if field == :a
        getfield(x, :a)
    else
        error("Not a public property")
    end
end

function getallproperties(x::MyType, field::Symbol)
    getfield(x, field)
end

function Base.getproperty(x::MyType, field::Symbol; public = true)
    if public
        getpublicproperties(x, field)
    else
        getallproperties(x, field)
    end
end

then you get:

julia> x = MyType(1, 2)
MyType(1, 2)

julia> x.a
1

julia> x.b
ERROR: Not a public property
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] getpublicproperties at ./REPL[2]:5 [inlined]
 [3] #getproperty#4 at ./REPL[8]:3 [inlined]
 [4] getproperty(::MyType, ::Symbol) at ./REPL[8]:2

julia> getproperty(x, :b, public = false)
2

I am sure you can do some macro-magic to define these things nicely.

9 Likes