Variables and Assignments
So far, we have been evaluating individual Smalltalk expressions and displaying the results. A Smalltalk program of any real value must consist of many such expressions and, for them to be useful, it's going to be important to store the results somewhere. All computer languages use variables in which to place intermediate values so that they can be retrieved at a later time.
In Smalltalk, a variable is a named slot or placeholder into which any object can be stored. A variable name must begin with a letter but subsequently, may consist of any letter, number or underscore characters. The following are valid variable names:
Although the last variable, day_of_week, is a valid name, in Smalltalk it is conventional to compose this without the underscore characters but by capitalizing subsequent words. Thus, dayOfWeek would be the preferred name.
You can store an object into a variable using an assignment. Try the following breakdown of Pythagoras' theorem. If you wish, you can just evaluate (using Ctrl+E) the first few lines and only display the answer (using Ctrl+D) for the last line.
a := 6.
b := 7.
hypotenuseSquared := a squared + b squared. "By Pythagoras"
hypotenuse := hypotenuseSquared sqrt.
Perhaps you've noticed something else new here in addition to the use of the assignment (:=) operator. The Smalltalk language uses a full stop or period (.) to separate individual expressions. Now you can evaluate several expressions in one go. Try the above example again but this time select all of the text before asking to display the result.
One thing that is different between Smalltalk variables and those used in other languages is that they are un-typed. A Smalltalk variable is just a slot capable of holding any object; you do not have to declare a variable as being able to hold only a particular type. This makes Smalltalk variables very much easier to use and, in the end, more flexible.
Tip: the un-typed nature of Smalltalk variables is often cited as an indication that Smalltalk is not a "safe" language. Languages with strongly typed variables, that insist on a variable being declared as able to hold only a particular type of value, are seen as being safer because the compiler can perform more checks and therefore reduce the number of problems that arise at runtime.
However, Smalltalk IS eminently type safe. Even if an incorrect class of object is placed in a variable slot, the problem will not go unnoticed during runtime testing. The object will not respond to the same set of messages that will be expected of it and will throw up a Walkback dialog when an unsuitable message is not understood.
Dolphin Smalltalk supports three different types of variables, Workspace, Temporary, Instance and Global.