How to use union in "if" statement [Crystal] -


following code works , print "5.0"

$x : float64 $y : float64 $x = 3.0_f64 $y = 2.0_f64 puts $x + $y 

now, change code support "nil".

$x : float64? $y : float64? $x = 3.0_f64 $y = 2.0_f64 puts $x + $y if !$x.nil? && !$y.nil? 

however code reports following error message.

 no overload matches 'float64#+' 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 these types:  - float64#+(nil)      puts $x + $y if !$x.nil? && !$y.nil? 

i stop call of method "#+()" if $x or $y nil , print calculated result if both float64.

what best practice situation?


in above code, simplified code question. in result, meaning of question changed involuntarily.. wanted ask following code actually.

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 

this code, reports following error.

 instantiating 'xyz#do_calc()'  x.do_calc   ^~~~~~~  in ./a.cr:15: no overload matches 'float64#+' 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 these types:  - float64#+(nil)        puts @a + @b 

how can avoid error?

be sure read docs if, , checking nil: https://crystal-lang.org/docs/syntax_and_semantics/if_var.html , https://crystal-lang.org/docs/syntax_and_semantics/if_var_nil.html

this applies local variables, you'll need assign values local variables first.

as side note, global variables don't exist anymore in language of crystal 0.19.0.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -