This is my code:
x := 22 storeString.
y := x + x.
Transcript show: y.
Expected output: 2222 Actual output: 44.
I thought that the storeString
message, sent to 22, assigned to x, would result in a string value being stored into x.
So I thought, I'm pretty new in smalltalk. Maybe it's order of operations? So I tried this:
x := (22 storeString).
y := x + x.
Transcript show: y.
Same result, and same, if I use printOn
instead of storeOn
. This is probably a day-one tutorial-following type question. But what is going on? Note that I know about the concatenation operator (,) but I am still wondering how it is that you can add two strings together like this? Is some implicit conversion from string back to integer happening as part of +
?
#+
is implemented on String
and does a coercion to a Number
before doing the addition.
Squeak has lot of eToys (a Smalltalk variation for kids) code spread throughout its core codebase. This is likely the reason why String
implements all math operators. In Pharo the math operators have been mostly removed from String
, so '1' + '2'
raises an error like in any other Smalltalk.