4 ms·
What would you expect string + number to do?
by SimeVidas 6y ago
What would you expect string + number to do?
- phinnaeus 6y agoIncompatible types error, either at runtime or during compilation depending on the language
- weare138 6y agoKind of depends on the language. Perl converts the string to an integer if you use a math operator on a numeric string. Python just throws an error.
- erik_seaberg 6y agoWhen I want either addition or string concatenation, I know it, I can't think of a use case where I'm happy getting either randomly. Perl got this right: 2 + 2 == 4 2 . 2 eq 22 You can even declare that failed conversions should throw: use warnings FATAL => qw(numeric)
- sergeykish 6y agoYes, perl is consistent perl print "2" + 1 3 print "2" - 1 1 js > "2" + 1 "21" > "2" - 1 1
- weare138 6y agoAnother thing I thought was clever about Perl is it has two comparison operators, '==' for numeric values and 'eq' for strings.
- sergeykish 6y agoruby >> +"2" => "2" >> "2" + 1 TypeError (no implicit conversion of Integer into String) python >>> +"2" TypeError: bad operand type for unary +: 'str' >>> "2" + 1 TypeError: can only concatenate str (not "int") to str lua > +"2" stdin:1: unexpected symbol near '+' > "2" + 1 3.0
- hajile 6y agoIn this case, they could be copying Java which allows an implicit cast from number to string.