Julia: Override method to add functionality

Viewed 148

I would like to extend an abstract type's method in a concrete type. I can do it with a new method but this introduces more complexity:

abstract type AbstractTask end
function complete(task::AbstractTask)
    complete_concrete_task(task)
    println("Done!")
end

struct Task <: AbstractTask
    name::String
end
complete_concrete_task(task::Task) = println(task.name)
coding = Task("coding")
complete(coding)

In Python, I would use the super operator. Is there an equivalent in Julia?

Thanks in advance!

1 Answers

I would say that using dispatch the way you did introduces much less cognitive complexity than a call to super. But you can use invoke select methods of supertypes:

julia> abstract type AbstractTask end

julia> function complete(task::AbstractTask)
           println("Done!")
       end
complete (generic function with 1 method)

julia> struct Task <: AbstractTask
           name::String
       end

julia> complete(task::Task) = (println(task.name); invoke(complete, Tuple{AbstractTask}, task))
complete (generic function with 2 methods)

julia> coding = Task("coding")
Task("coding")

julia> complete(coding)
coding
Done!

Of course this requires you not to forget to add it to every subtype method, which is the additional complexity I mean.

The good thing is that invoke with a constant type parameter will be compiled away (or so I have read), so there's not even overhead from dispatch.

Related