Crystal: Nil compilation error when dividing even though checking for Nil

Created on 1 Jul 2017  路  6Comments  路  Source: crystal-lang/crystal

Hey,

I get an undefined method '/' for Nil (compile-time type is (Int32 | Nil)) at day/7 when trying to divide a variable by an Integer, even though I am explicitly doing a Nil check beforehand.

class MyClass
  property day : (Nil | Int32)

  def initialize(@day = nil)
  end

  def some_method
    # no matter what check I add, doesn't work
    return if day.nil?
    unless day.nil?
      if day
        day/7
      end
    end
  end
end
puts MyClass.new(13).some_method

Same thing if I remove the property and use the instance variable directly. def initialize(@day : (Nil | Int32) = nil)

Any thoughts on this?

Crystal 0.22.0 (2017-04-20) LLVM 4.0.0

Most helpful comment

@bew You made my stream rainbow-ish, thanks! :)
image

All 6 comments

try this way

class MyClass
  property day : (Nil | Int32)

  def initialize(@day = nil)
  end

  def some_method
    # no matter what check I add, doesn't work
    return if day.nil?
    unless day.nil?
      if tday = day
    tday/7
      end
    end
  end
end
puts MyClass.new(13).some_method

The behaviour is described in docs: https://crystal-lang.org/docs/syntax_and_semantics/if_var.html
Of course, any check will work - return, unless, not just if, just assign to local variable instead of checking a property.

Ah, interesting, I wasn't aware of the difference between instance and local variables in this case. Thanks!

You were not even using an instance var (at least not directly), but an instance method.

Shorter code:

class MyClass
  property day : Int32?

  def initialize(@day = nil)
  end

  def some_method
    return unless day = @day
    day / 7 # it will use the variable defined above
  end
end

puts MyClass.new(13).some_method

@bew You made my stream rainbow-ish, thanks! :)
image

Was this page helpful?
0 / 5 - 0 ratings