How can a variable be fun? With Cuis-Smalltalk, a variable is the name of a box that holds a value – an object, that’s it!
A variable can hold a value of any class. The value is strongly typed (we can always determine its Class), but the variable (box) is not restricted to holding a value of a single type.
One important direct consequence is that the type of a variable – i.e. the class of the referenced object – can change over time. Observe this example:
| a | a := 1 / 3. a class ⇒ Fraction a := a + (2 / 3) ⇒ 1 a class ⇒ SmallInteger
The initial value of the variable a
was a Fraction
instance, after some calculation it ends as a SmallInteger
instance.
In fact, there is no such thing as type, it is only referenced objects which can mutate over time into other kind of object: a metal body structure to which you add two wheels may become a bicycle, or a car if you add four wheels.
Therefore, to declare a method variable we just name it at the beginning of the script and surround it with pipe characters “|”.
A variable always holds a value. Until we place a different value
into a variable, the variable holds the nil
value, an
instance of UndefinedObject
. When we say that a value is
bound to a variable we mean that the named box now holds that
value.
So far we sent messages directly to objects, but we can send messages to a variable bound to an object too.
Any object responds to the message #printString
.
| msg | msg := 'hello world!'. Transcript show: msg capitalized printString, ' is a kind of '. Transcript show: msg class printString; newLine. msg := 5. Transcript show: msg printString, ' is a kind of '. Transcript show: msg class printString; newLine.
This ease of use has a drawback: when writing code to send a message to a variable bound to an object, the system does not check ahead of time that the object understands the message. Nevertheless, there is a procedure to catch this kind of situation when the message is actually sent.