The reason is that Crystal performs NULL checks at compile time. The compiler is telling you that when you are trying to add 2 values there can be NULL values there (
nil in Crystal and
Nil is corresponding type).
You are using
gets method which can return
nil IO - Crystal 1.1.1 (see method return type is
String? which is shortcut for writing union type explicitly like
String | Nil). That’s why you get this error.
To make sure your code works you need to add explicit checks for case when values can be
nil. You can use
if/else for that.
Also in Crystal local variable names are lowercase like
local_var_name and names starting with capital letters are for constants, classes, etc.
So use something like that:
a = gets
b = gets
if a && b
x = a + b
x = nil
And here is an example output:
x # => "12"
"12" which is string because
gets returns strings and strings can be concatenated with
See also how
p! x prints both the expression
x and it’s value
"12". You might use
pp! macros for debugging purpose. See for example Top Level Namespace - Crystal 1.1.1)-macro