November 12, 2019

Smalltalk Assignment

 

To create an instance of the class Frog we evaluate
Frog new

For the Smalltalk system to reference this object, it needs to be given a variable. This is achieved by assignment.
frog1 := Frog new

This code means, evaluate the expression Frog new on the right of the assignment operator := and assign the object that is returned as the message answer to the variable frog1. Now frog1 can be sent messages.

Consider the following expression series.

frog1 := Frog new.
frog2 := Frog new.
frog1 := frog2

The first two lines create two instances and assign them to the variables frog1 and frog2. The third line takes the object referenced by frog2 and assigns it to the variable frog1. Consequently, the object referenced by frog2 is now also referenced by frog1. The object that was referenced by frog1 is no longer referenced and is garbage collected. I will return to this matter later when using variable-reference diagrams to help understand this process.

I have already mentioned literals. For instance 123 is a number literal and it references an instance of the class SmallInteger. However, it is possible to assign a literal to a variable
x := 123

Now consider the following

x := 123.
y := 123.
x := y

The first two lines take the instance of SmallInteger referenced by 123 and assign it first to the variable x and then to the variable y. The third line assigns the object referenced by y to the variable x. Consequently, the literal object referenced by 123 is also referenced by two variables x and y. At no stage has garbage collection taken place, which is just as well as we would get into problems if literals could be destroyed. We could omit the first line of code, which is superfluous, and arrive at the same situation of having this number object referenced by two variables. Smalltalk does not permit assignment of literals to other literals.

123 := 124 "Illegal!"

A final point to appreciate, assignment does not involve any message sending.

Next page » Methods

Previous page « Messages

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page