The Crystal Programming Language Forum

How to use union type (T | Nil)?

i have a class

class Node
    @size : Int32?
    @word : String?
    property word
    def size : Int32
        @size ||= @word.not_nil!.size
        @size
    end
 end

 n = Node.new
 n.word = "hello"

 p n.size

when i execute crystal src/node.cr i got error

In src/node.cr:5:16

 5 | def size : Int32
                ^
Error: method must return Int32 but it is returning (Int32 | Nil)

then , i change code to this

class Node
    @size : Int32?
    @word : String?
    property word
    def size : Int32
        @size ||= @word.not_nil!.size
        return 0 if @size.nil?
        @size.to_i32
    end
 end

 n = Node.new
 n.word = "hello"

 p n.size

got the same error. What am I supposed to do?

return 0 if @size.nil? doesn’t remove Nil from @size's types in the next line like it seems you’re expecting. You can only do that with local variables.

I would do this if you’re not sure if @word could be nil:

class Node
  @size : Int32?
  @word : String?

  property word

  def size : Int32
    @size ||= @word.try &.size || 0
  end
end

And this otherwise:

class Node
  @size : Int32?
  @word : String?

  property! word

  def size : Int32
    @size ||= word.size
  end
end
1 Like

@Exilor thanks. :smile: