以下代码可以正常工作并打印出“5.0”。
然而,此代码报告以下错误信息。
$x : Float64
$y : Float64
$x = 3.0_f64
$y = 2.0_f64
puts $x + $y
现在,我改变了代码以支持“nil”。
$x : Float64?
$y : Float64?
$x = 3.0_f64
$y = 2.0_f64
puts $x + $y if !$x.nil? && !$y.nil?
然而,此代码报告以下错误信息。
没有重载与类型(Float64 | Nil)匹配的'Float64 #+'。
重载是:
- Float64#+(other : Int8)
- Float64#+(other : Int16)
- Float64#+(other : Int32)
- Float64#+(other : Int64)
- Float64#+(other : UInt8)
- Float64#+(other : UInt16)
- Float64#+(other : UInt32)
- Float64#+(other : UInt64)
- Float64#+(other : Float32)
- Float64#+(other : Float64)
- Number#+()
找不到这些类型的重载:
- Float64#+(Nil)
如果$x或$y为空,则停止调用方法“#+()”,如果两者都为Float64,则打印计算结果。
在这种情况下,最佳实践是什么?
在上面的代码中,我简化了此问题的代码。但结果意外地改变了问题的含义。实际上,我想问以下代码。
class Xyz
property a, b
@a : Float64?
@b : Float64?
def initialize
@a = nil
@b = nil
end
def do_calc
if !@a.nil? && !@b.nil?
puts @a + @b
else
puts "We can't calculate because '@a or @b has nil."
end
end
end
x = Xyz.new
x.a = 3.0_f64
x.b = 2.0_f64
x.do_calc
这段代码报告了以下错误。
正在实例化'Xyz#do_calc()'
x.do_calc
^~~~~~~
在./a.cr:15中:没有重载与类型(Float64 | Nil)匹配的'Float64#+'。
重载是:
- Float64#+(other:Int8)
- Float64#+(other:Int16)
- Float64#+(other:Int32)
- Float64#+(other:Int64)
- Float64#+(other:UInt8)
- Float64#+(other:UInt16)
- Float64#+(other:UInt32)
- Float64#+(other:UInt64)
- Float64#+(other:Float32)
- Float64#+(other:Float64)
- Number#+()
找不到这些类型的重载:
- Float64#+(Nil)
puts @a + @b
如何避免这个错误?