The idiomatic way would be like:
def addme(a : Int32?, b : Int32?) : Int32?
return unless a && b
a + b
end
To handle nil
you need to either use the special .nil?
method, .try
, or just check the variables directly as nil
is a falsely value so the compiler can know they won’t be nil
. !=
does not work because it’s possible to override it to return whatever, so the compiler cannot trust it.
Another way would be to have two overloads of the method, one only accepting Int32
and the other accepting Int32?
with the former just being a + b
and the latter nil
return values.
EDIT: Maybe also checkout [Screencast] Handling Nil in Crystal