Function Definition Precedence

How do function definition precedence work?

julia> function f()
           begin
               try
                   return 1
               finally
                   return 2
               end
           end
       end
f (generic function with 2 methods)

julia> f()
2

julia> function f(x::Any = "test")
           begin
               try
                   return 3
               finally
                   return 4
               end
           end
       end
f (generic function with 2 methods)

**julia>** f()

4

julia> function f()
           begin
               try
                   return 1
               finally
                   return 2
               end
           end
       end
f (generic function with 2 methods)

julia> f()
2

this may help https://docs.julialang.org/en/v1.2-dev/base/base/#try
finally is always run, even with return in the try part.

1 Like

When you define:

function f(x::Any = "test")
  begin
      try
          return 3
      finally
          return 4
      end
  end
end

It actually defines 2 methods, one that takes an argument and one that doesn’t:

julia> methods(f)

# 2 methods for generic function "f":
[1] f() in Main at none:2
[2] f(x) in Main at none:2

So when you define f() again it overwrites the f method that takes no parameters.

2 Likes