Search code examples
crystal-lang

Overload method with named arguments in Crystal?


Is it possible to overload methods based on argument names, when they have the same type?

def inspect(url : String); inspect_url(url) end
def inspect(path : String); inspect_path(path) end

# Always will be called with explicit names
inspect url: "some url"
inspect path: "some path"

# Never without names, this form is not needed 
# and never will be used
inspect "something"

Solution

  • Arguments after a splat argument can only be passed as named arguments. The typical usage is to have an unnamed splat argument followed by named arguments.

    def inspect(*, url : String)
      "inspect url"
    end
    
    def inspect(*, path : String)
      "inspect path"
    end
    
    inspect url: "some url"   # => "inspect url"
    inspect path: "some path" # => "inspect path"
    
    inspect "something" # Invalid number of arguments