Search code examples
crystal-lang

Are double splats treated differently in methods?


When I used a double splat for a method, I'm not allowed to define a variable with a type within the method:

def show(**attrs)
  place : String = "w"
  puts place
end

show(name: "Bobby")  # This works.

show(name: "Bobby", place: "World") # This fails:
#
#in tmp.cr:2: variable 'place' already declared
#
#  place : String = "w"
#  ^~~~~

Is this the expected behaviour when using double splats? I couldn't find anything in the Crystal Book about this: https://crystal-lang.org/docs/syntax_and_semantics/splats_and_tuples.html


Solution

  • This is a bug, please report it as such.

    Note that declaring local variables with a type is not a recommended practice. Because it was a recent addition, it is not well tested and apparently prone to bugs.

    You can see that this works, anyway:

    def show(**attrs)
      place = "w"
      puts place
      puts attrs[:place]
    end
    
    show(name: "Bobby", place: "World")
    
    w
    World