Skip to content

Instantly share code, notes, and snippets.

@j-fu
Last active October 23, 2025 06:15
Show Gist options
  • Select an option

  • Save j-fu/b9dda88670751ca52b08361a768df3b4 to your computer and use it in GitHub Desktop.

Select an option

Save j-fu/b9dda88670751ca52b08361a768df3b4 to your computer and use it in GitHub Desktop.
import Base
using Test
struct Grid
_components::Dict{DataType, Any}
end
function makecomponent(x, g)
return nothing
end
function makecomponent(::Type{Val{:b}}, g)
return 13
end
function makecomponent(::Type{Val{:x}}, g)
return 19
end
function Base.getproperty(g::Grid, s::Symbol)
if s == :_components
return getfield(g, s)
else
components = getfield(g, :_components)
if !haskey(components, Val{s})
c = makecomponent(Val{s}, g)
if isnothing(c)
@warn "cannot make component $s"
else
@info "made component $s"
components[Val{s}] = c
end
end
getindex(components, Val{s})
end
end
function Base.setproperty!(g::Grid, s::Symbol, v)
return if s == :_components
error("wrong access")
else
setindex!(getfield(g, :_components), v, Val{s})
end
end
g = Grid(Dict{DataType, Any}())
@testset "xgrid" begin
g.a = 1
@test g.a == 1
g.c = 3
@test g.c == 3
y = g.b
@test y == 13
end
try
local y = g.y
catch e
@warn "detected error"
end
abstract type AbstractGridComponent end
struct AType <: AbstractGridComponent end
struct BType <: AbstractGridComponent end
struct XType <: AbstractGridComponent end
tsym(::Type{AType}) = :a
tsym(::Type{BType}) = :b
tsym(::Type{XType}) = :x
Base.getindex(g::Grid, T::Type{<:AbstractGridComponent}) = getproperty(g, tsym(T))
@testset "xgrid[Type]" begin
@test g[AType] == 1
xx = g[XType]
@test xx == 19
end
g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment