Crystal: Can't declare method ==(*args)

Created on 24 Nov 2020  路  1Comment  路  Source: crystal-lang/crystal

This code:

class Foo
  def ==(*args)
    true
  end
end

won't compile, with the error:

crystal build foo.cr
In foo.cr:2:16

 2 | def ==(*args)
                  ^
Error: setter method '==' cannot have more than one argument

First, the error message is odd since == isn't a setter. Also, although *args is a catch-all for positional arguments, it isn't forcing the compiler to provide more than one argument to ==.

The reason I hit this is that I have my own delegate macro that does optional argument and return-value processing. I hacked in a one_argument option so that I could successfully delegate ==. I can't see why Object#delegate doesn't need to do this, unless there is compiler magic going on.

Most helpful comment

The error message can be improved, but the behaviour seems correct. Equality method requires exactly one argument, so a splat makes really no sense. The compiler should call that out.

Object#delegate handles methods ending in = explicitly:
https://github.com/crystal-lang/crystal/blob/48ebe7b809ebebc6a2360d043b58726a569533f2/src/object.cr#L1247

>All comments

The error message can be improved, but the behaviour seems correct. Equality method requires exactly one argument, so a splat makes really no sense. The compiler should call that out.

Object#delegate handles methods ending in = explicitly:
https://github.com/crystal-lang/crystal/blob/48ebe7b809ebebc6a2360d043b58726a569533f2/src/object.cr#L1247

Was this page helpful?
0 / 5 - 0 ratings