Reputation: 6870
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 ?
Upvotes: 1
Views: 50
Reputation: 34116
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
Upvotes: 4