Search code examples
crystal-lang

Named arguments shortcut for Crystal


In code below named arguments have to be duplicated, is there a way to shorten the expression?

struct Figure
  getter id :      String
  getter hash :    String
  getter title :   String

  def initialize(@id, @hash, @title)
  end
end

id = "Figure 1", hash = "123", title = "Some figure"

Figure.new id: id, hash: hash, title: title

Something like code below, yet keep it named not positional?

Figure.new id, hash, title

or maybe

Figure.new{ id, hash, title }

Solution

  • I don't know of a way to shorten this.

    I think this would be a dangerous semantic when you tie the names of local variables to the names of method arguments because changing things on one place would have unforeseeable effects in another place.

    Using positional arguments should be fine for most use cases. And in cases where you want to skip some arguments, you can just combine positional and named arguments.