Multiple Dispatch - Call Abstract Type Function

I’m new to Julia and I have a problem with multiple dispatch. Consider below code:

abstract type A end

struct A1<:A end
struct A2<:A end

foo(a::A) = println("It's A")

function foo(a::A1)
    # Do Something with A1 type object and then call foo(a::A)
    foo(a)
end

I create two objects a1 and a2

a1 = A1()
a2 = A2()

Now when I call foo(a1) I get StackOverFlow Error. I understand that it’s getting recursive, but I want to do some other operations before I call foo(a::A) type function for A1 type object.

ERROR: StackOverflowError:
Stacktrace:
 [1] foo(::A1) at ./REPL[5]:3 (repeats 79984 times)

Calling foo(a2) doesn’t give any error.

It's A

Inside of foo(a1) you are calling foo(a1 :: A1) again. Hence you have infinite recursion and stack overflow.

To avoid this, consider factoring out the generic part into a separate function:

foo_common(a :: A) = println("It is A");

foo(a :: A) = foo_common(a);

function foo(a :: A1)
  # other things
  foo_common(a);
end
8 Likes

There is also invoke, however, @hendri54’s solution is more Julian, imo.