When I was writing some code that needs
Int64 as part of the initialization, found that automatic casting of Int32 args to Int64 on a method only works if the method has the variable type in the signature.
class Foo getter id : Int64 def initialize(@id) end end pp Foo.new(1) # Error: instance variable '@id' of Foo must be Int64, not Int32
@id has been defined with the right type, is not automatically casted.
However, when re-adding it to the method, it works:
class Foo getter id : Int64 def initialize(@id : Int64) end end f = Foo.new(1) # OK, no error puts typeof(f.id) # => Int64
I normally duplicate the types of the instances in the method signature, but was wondering if this is intentional or I might be missing something.
Update: found in the Crystal Book the reference to autocasting:
Autocasting at the moment works only in two scenarios: at function calls, as shown so far, and at class/instance variable initialization.