# Type stable specializations of \`getproperty\` without code duplication?

**URL:** <https://discourse.julialang.org/t/type-stable-specializations-of-getproperty-without-code-duplication/92404>\
**Category:** Performance\
**Tags:** type-stability\
**Created:** [January 2, 2023, 4:10am UTC](https://discourse.julialang.org/t/type-stable-specializations-of-getproperty-without-code-duplication/92404 "2023-01-02T04:10:12Z")\
**Posts on this page:** 1\
**Page:** 2

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 2, 2024, 2:12pm UTC](https://discourse.julialang.org/t/type-stable-specializations-of-getproperty-without-code-duplication/92404/21 "2024-09-02T14:12:56Z")

</div>

Reviving this topic instead of opening a new one, hope that is OK.

I found that with something like the following tiny utility function, one can automate the fallback to `getfield` in Julia 1.10:

```julia
Base.@constprop :aggressive function getfield_or_dispatch(value::T, key::Symbol) where T
    @assert isstructtype(T)
    if key ∈ fieldnames(T)
        getfield(value, key)
    else
        _getproperty(value, Val(key))
    end
end

```

Eg

```julia
@inline function Base.getproperty(foo::Foo, key::Symbol)
    getfield_or_dispatch(foo, key)
end

_getproperty(foo::Foo, ::Val{:calculated}) = 1

```

is then inferred in the contexts I have tested.

Now I am wondering whether to package this up in a tiny library, and if yes, what the API should be. A macro could take care of the `getproperty` indirection. And I defining methods for `getproperty(foo, ::Val{thingy})` is not technically type piracy but a bit smelly.

[Previous page](https://discourse.julialang.org/t/type-stable-specializations-of-getproperty-without-code-duplication/92404.md?page=1)
