The problem is the following:
I have an abstract type MyAbstract
and derived composite types MyType1
and MyType2
:
abstract MyAbstract
type MyType1 <: MyAbstract
somestuff
end
type MyType2 <: MyAbstract
someotherstuff
end
I want to specify some general behaviour for objects of type MyAbstract
, so I have a function
function dosth(x::MyAbstract)
println(1) # instead of something useful
end
This general behaviour suffices for MyType1
but when dosth
is called with an argument of type MyType2
, I want some additional things to happen that are specific for MyType2
and, of course, I want to reuse the existing code, so I tried the following, but it did not work:
function dosth(x::MyType2)
dosth(x::MyAbstract)
println(2)
end
x = MyType2("")
dosth(x) # StackOverflowError
This means Julia did not recognize my attempt to treat x
like its "supertype" for some time.
Is it possible to call an overloaded function from the overwriting function in Julia? How can I elegantly solve this problem?
You can use the invoke
function
function dosth(x::MyType2)
invoke(dosth, (MyAbstract,), x)
println(2)
end
With the same setup, this gives the follow output instead of a stack overflow:
julia> dosth(x)
1
2
Discussion can be found here on replacing or improving the interface to invoke
. My proposal would make the syntax very close to what you wrote in your question:
function dosth(x::MyType2)
@invoke dosth(x::MyAbstract)
println(2)
end
If you have any thoughts on what a more intuitive name than "invoke" would be, please post a comment below.
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