So I want to extend getproperty
(and likewise setproperty!
) for a custom type, a bit like what LinearAlgebra.LU
does. I see that this is usually done with an if/else
chain; however, this is not very Julian in style, and moreover I would like to keep the list open if possible, and to do this for a lot of types without copying too much boilerplate code.
So I came up with the following solution, which allows me to add a custom property to a custom type in a one-liner if needed, at the cost of inserting some Val
.
@inline getproperty(x, s::Symbol) = _getproperty(x, Val(s)) # <- ☠ type piracy, arrh!
@inline _getproperty(x, ::Val{S}) where{S} = Base.getfield(x, S)
# ...
function _getproperty(x::MyType, ::Val{:myfield})
#...
end
The two first lines ensure that, for types for which I do not define _getproperty
, this will be equivalent to the definition in Base.jl
.
Is there anything wrong with this solution (apart from style points lost for type piracy)? Is there a special case which I missed? Will this compile to hundreds of specialized functions, or will it all be silently inlined? Are the @inline
macros even useful here? Will this also work for setproperty!
? Would it be better if I wrote a big @generated
function looking if a method exist for _getproperty
?