Refactoring into parent type possible?

suppose an abstract type R has several concrete children types, say S and T, i.e. S <: R and S <: T. Now, a function fun is overloaded on every child of R like:

function fun(x::S)
   @assert common_check(x)
  return S_specific(x)
end

function fun(x::T)
   @assert common_check(x)
  return T_specific(x)
end

It would be nice to be able to refactor common_check(), in the following imaginative manner:

function fun(x::R)
  @assert common_check(x)
  # ??? then, how to dispatch???
end

function fun(x::S)
  return S_specific(x)
end

function fun(x::T)
  return T_specific(x)
end

how could it be done??? the problem is: if I call fun(::S) or fun(::T), fun(::R) would not be called at all. Thanks.

The following pattern is quite common:

function fun(x::R)
    @assert common_check(x)
    return _fun(x)
end

_fun(x::S) = S_specific(x)
_fun(x::T) = T_specific(x)
2 Likes

oic (use another function name).

what if the function is (*)? what should be the name of “_fun”?

It doesn’t matter. The choice is up to you.

You can prefix * with _ too:

julia> @eval $(Symbol("_*"))(x) = "Hello, $x"
_* (generic function with 1 method)

julia> getfield(Main, Symbol("_*"))("tomtom")
"Hello, tomtom"

:troll:

3 Likes