Hi,
I’m completely new to Julia and I’m trying to reuse some of my tricks from matlab to prevent my programs from degenerating to passing around deep hierarchical state struct arrays and having alot of code doing index alignment.
I found this post which had a neat trick using closures to achieve what I (think I) want (see first answer):
https://stackoverflow.com/questions/39133424/how-to-create-a-single-dispatch-object-oriented-class-in-julia-that-behaves-l
However, I found that when I add default values to the returned functions they become boxed. What is the reason for this and is it a sign of something bad?
For example:
function funcs()
function boxed(str::String = "default")
println(str)
end
function notboxed(str::String)
println(str)
end
return () -> (boxed; notboxed)
end
julia> fs = funcs()
#205 (generic function with 1 method)
julia> fs.boxed
Core.Box(getfield(Main, Symbol("#boxed#206"))())
julia> fs.notboxed
(::getfield(Main, Symbol("#notboxed#207"))) (generic function with 1 method)
Adding an unboxing method lets me circumvent this, so it appears as if the functions work as intended:
function funcs()
function boxed(str::String = "default")
println(str)
end
function notboxed(str::String)
println(str)
end
return unbox(() -> (boxed; notboxed))
end
function unbox(funcs)
unboxed = funcs.boxed.contents
notboxed = funcs.notboxed
() -> (unboxed, notboxed)
end
julia> fsu = funcs()
#215 (generic function with 1 method)
julia> fsu.unboxed
(::getfield(Main, Symbol("#boxed#212"))) (generic function with 2 methods)
julia> fsu.unboxed()
default
It does however feel a bit silly to always have to wrap things in unboxers like this. Is there a way to avoid the boxing?