I am very excited about getproperty
& friends in 1.0, as it would make a particular package I am working on have a much simpler API. I could not find a lot of guidance about it though at the moment, so I am learning from the examples (eg in LinearAlgebra
).
I am wondering about the possibility of “forwarding” all properties which are not fields to a particular field. MWE:
import Base: propertynames, getproperty
"Subtypes have a field `x`, used for properties not in `fieldnames`."
abstract type ForwardOnX end
propertynames(w::ForwardOnX) = (fieldnames(w)..., propertynames(w.x)...)
function getproperty(w::TX, name::Symbol) where {TX <: ForwardOnX}
if name ∈ fieldnames(TX)
getfield(w, name)
else
getproperty(w.x, name)
end
end
struct Test0{A}
a::A
end
struct Test1{X,B} <: ForwardOnX
x::X
b::B
end
t0 = Test0(:a)
t1 = Test1(t0, :b)
t0.a # :a
t1.a # :a
t1.b # :b, the relevant field
t1.x # the relevant field
Is this an OK pattern? I am hoping it would compile to reasonably efficient code with constant folding. Anything I could do to improve it?