Skip to content

Instantly share code, notes, and snippets.

@christopher-dG
Created March 11, 2019 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christopher-dG/49a600b680cf692bb9947f7a20f5ac20 to your computer and use it in GitHub Desktop.
Save christopher-dG/49a600b680cf692bb9947f7a20f5ac20 to your computer and use it in GitHub Desktop.
Silly POC of OO-style instance methods in Julia
tablename(x::Symbol) = Symbol(:methtab_, x)
macro instancemethod(T::Symbol, ex::Expr)
@assert ex.head (:function, :(=))
table = tablename(T)
name = ex.args[1].args[1]
insert!(ex.args[1].args, 2, :(this::$T))
quote
$(esc(ex))
$table[$(QuoteNode(name))] = $name
end
end
macro OO(ex::Expr)
@assert ex.head === :struct
T = ex.args[2]
table = esc(tablename(T))
quote
const $table = Dict{Symbol, Function}()
$(esc(ex))
function Base.getproperty(x::$T, name::Symbol)
return if haskey($table, name)
(args...; kwargs...) -> $table[name](x, args...; kwargs...)
else
getfield(x, name)
end
end
end
end
@OO mutable struct Foo
x::Int
end
@instancemethod Foo set_x(x::Int) = this.x = x
f = Foo(1)
f.set_x(10)
@show f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment