2016-09-07 23 views
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 

如何避免此错误?

回答

4

请务必阅读的文档有关,如果,并检查零:https://crystal-lang.org/docs/syntax_and_semantics/if_var.htmlhttps://crystal-lang.org/docs/syntax_and_semantics/if_var_nil.html

这仅适用于局部变量,所以你需要的值先分配给本地变量。

作为一个附注,全局变量在Crystal 0.19.0中不再存在。

+0

谢谢你的问题。我简化了这个问题的代码。 在结果中,问题的含义被不自觉地改变了.. 我添加了我想要问的问题.. – elgoog

+0

我在你指定的链接中找到了答案。对不起,重复的问题。 – elgoog