I am trying to call a general method from a specific one, but cannot figure out how.
function fn(x)
# generic
...
end
function fn(x :: String)
# I want to call the generic version here
val = fn(x)
# do something with val and then return it
...
end
Is this possible?
A workaround is using a helper function that can be called from both generic and specific methods. e.g.
function helper(x)
# main work is here
...
end
function fn(x)
# generic
helper(x)
end
function fn(x :: String)
val = helper(x)
# now use the val to do something
...
end
Without using such helpers, is there a way to control the dispatch to select a particular method to use? Is there something like :before
and :after
keywords and call-next-method
from lisp CLOS in Julia?
You can use the invoke
function:
julia> function fn(x)
@info "generic $x"
end
fn (generic function with 1 method)
julia> function fn(x :: String)
@info "before"
invoke(fn, Tuple{Any}, x)
@info "after"
end
fn (generic function with 2 methods)
julia> fn(10)
[ Info: generic 10
julia> fn("10")
[ Info: before
[ Info: generic 10
[ Info: after
(just to be clear - the printing of "before"
and "after"
is only to highlight what gets executed in what sequence - the only thing that is related to method dispatch here is the invoke
function)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With