There is no workaround. nil is a special value in Crystal. The compiler can’t allow any other value to pose as nil with returning true for #nil?. Else the type system would break.
So you can’t have your return value fulfill a be_nil expectation. be_nil is essentially a type check like be_a(Nil) which an object of type Hashr can’t satisfy.
The same applies to JSON::Any wrapping a nil value, btw.
x = rand < 0.5 ? 1 : nil
# Here x is of type (Int32 | Nil)
if x.nil?
# Here x is guaranteed to be Nil
else
puts x + 2 # This works because the compiler knows this can't be Nil
end
If you were allowed to redefine nil? and return true for something that’s actually not exactly Nil, the above guarantees don’t hold anymore.