Understanding generic functions and docstrings

Hi!

Julia newcomer here who is trying to understand generic functions.

Consider the following two blocks of code:

abstract type A end

"""
Function that does something.
"""
somefunction(t::A)

struct B <: A
    # Code
end

struct C <: A
   # Code 
end

function somefunction(t::B)
    # Code
end

function somefunction(t::C)
    # Code
end

and

abstract type A end

somefunction(t::A)

struct B <: A
    # Code
end

struct C <: A
   # Code 
end

function somefunction(t::B)
    # Code
end

function somefunction(t::C)
    # Code
end

It is easy to see that the second block will fail since type assertion is tried to be made for undefined variable t. However, I don’t understand why the first block of code works, where somefunction has docstring included. My first thought would have been to implement the generic function just as a function without body:

function somefunction(t::A) end

What you are seeing is documented here:
https://docs.julialang.org/en/v1.7/manual/documentation/#Functions-and-Methods-2

Your first block just adds documentation to the specific (non existing) method somefunction(::Any):

help?> somefunction()
  Function that does something.

Your second block fails, because you are just trying to call method somefunction(::A) with a parameter t which isn’t defined. If you define t it will fail, because there is no method somefunction(::A).

1 Like