Crystal: "Unwrapping" unrelated nilable values in case branches not working and not rejected by the compiler

Created on 10 Aug 2018  路  2Comments  路  Source: crystal-lang/crystal

def int? : Int32?
    2
end

case true
when x = int?
    puts x # not reached
else
    puts ":("
end

Most helpful comment

You probably wanted to write:

# Note that there's no case expression
case
when x = int?
  puts x
else
  puts ":("
end

All 2 comments

This:

case exp
when something
  do_something
else
  do_something_else
end

is rewritten to:

if something === exp
  do_something
else
  do_something_else
end

In your case, your code is equivalent to:

if (x = int?) === true
  puts x
else
  puts ":("
end

and 2 === true is false.

Everything is working as expected. This is not a bug.

You probably wanted to write:

# Note that there's no case expression
case
when x = int?
  puts x
else
  puts ":("
end
Was this page helpful?
0 / 5 - 0 ratings

Related issues

cjgajard picture cjgajard  路  3Comments

will picture will  路  3Comments

Papierkorb picture Papierkorb  路  3Comments

oprypin picture oprypin  路  3Comments

nabeelomer picture nabeelomer  路  3Comments