Set both default attribute and type of attribute

58 Views Asked by At

I want to define a class Person with a age attribute of type Int32 and specify a default value for it in case it's not provided. I know how to do the first one:

class Person

  def initialize(@age : Int32) 

  end

end

and the second one:

class Person

  def initialize(@age = 0) 

  end

end

But not how to do both. Is this possible ?

1

There are 1 best solutions below

0
On BEST ANSWER

The ability to do this was added relatively recently, and it seems to be missing in the documentation. This is the way to do it:

class Person
  def initialize(@age : Int32 = 0) 
  end
end

Note that by default the type is implied to be the same as that of the default value. For example:

class Person
  def initialize(@age = 0) 
  end
end

Person.new("a")
Error in line 6: instantiating 'Person:Class#new(String)'
in line 2: instance variable '@age' of Person must be Int32, not String