3
下面的代码工作良好,打印“5.0”如何使用联盟“if”语句[水晶]
$x : Float64
$y : Float64
$x = 3.0_f64
$y = 2.0_f64
puts $x + $y
现在,我更改代码以支持“无”。
$x : Float64?
$y : Float64?
$x = 3.0_f64
$y = 2.0_f64
puts $x + $y if !$x.nil? && !$y.nil?
但是,此代码报告以下错误消息。
no overload matches 'Float64#+' with type (Float64 | Nil) Overloads are: - 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#+() Couldn't find overloads for these types: - Float64#+(Nil) puts $x + $y if !$x.nil? && !$y.nil?
我想停止方法的调用“#+()”如果$ x或$ y是零 和打印计算结果,如果两者都Float64。
这种情况的最佳做法是什么?
在上面的代码中,我简化了这个问题的代码。 在结果中,问题的含义不由自主地改变了。 我想问下面的代码实际上。
class Xyz
property a, b
@a : Float64?
@b : Float64?
def initialize
@a = nil
@b = nil
end
def do_calc
if [email protected]? && [email protected]?
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
此代码报告以下错误。
instantiating 'Xyz#do_calc()' x.do_calc ^~~~~~~ in ./a.cr:15: no overload matches 'Float64#+' with type (Float64 | Nil) Overloads are: - 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#+() Couldn't find overloads for these types: - Float64#+(Nil) puts @a + @b
如何避免此错误?
谢谢你的问题。我简化了这个问题的代码。 在结果中,问题的含义被不自觉地改变了.. 我添加了我想要问的问题.. – elgoog
我在你指定的链接中找到了答案。对不起,重复的问题。 – elgoog