设置默认属性和属性类型
Set both default attribute and type of attribute
我想用 Int32 类型的 age
属性定义 class Person
并为其指定默认值以防未提供。
我知道第一个怎么做:
class Person
def initialize(@age : Int32)
end
end
第二个:
class Person
def initialize(@age = 0)
end
end
但不知道如何做到这两点。这可能吗 ?
执行此操作的功能是最近添加的,文档中似乎缺少它。这是这样做的方法:
class Person
def initialize(@age : Int32 = 0)
end
end
请注意,默认情况下,类型隐含为与默认值相同。例如:
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
我想用 Int32 类型的 age
属性定义 class Person
并为其指定默认值以防未提供。
我知道第一个怎么做:
class Person
def initialize(@age : Int32)
end
end
第二个:
class Person
def initialize(@age = 0)
end
end
但不知道如何做到这两点。这可能吗 ?
执行此操作的功能是最近添加的,文档中似乎缺少它。这是这样做的方法:
class Person
def initialize(@age : Int32 = 0)
end
end
请注意,默认情况下,类型隐含为与默认值相同。例如:
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