Navigation:  Tutorials > Beginners Guide to Smalltalk > Control Flow >

Comparing Objects

Previous pageReturn to chapter overviewNext page

Smalltalk compares two objects using boolean expressions. A boolean expression is one that yields a truth value, i.e. true or false. We can use a number of binary messages to perform comparisons. First of all make simon bigger than teresa and charlie and then let's try some comparisons expressions.

simon growBy: 10.


Display the results of the following comparisons:

simon radius > teresa radius.

simon radius < 100.

charlie radius = teresa radius.

charlie position ~= teresa position.


The final expression is comparing the two positions to see if they are unequal. It's interesting here to note that, in this comparison, we are testing the equality of two points (the previous three comparisons were between numbers). So the comparison messages are not just limited to number objects. But not all objects can be compared since it all depends on whether they respond to the appropriate comparison messages. Try:

charlie >= teresa.


You got a does not understand walkback because it does not really make sense to compare the magnitude of a circle with that of a triangle.

Tip: you might of course decide that you wanted to consider the magnitude of a shape to be its area and you wanted to be able to use comparison messages based on this fact. Later you'll see how to define new messages for particular classes of object. Hence, if you wish, you'll be able to implement the comparison messages for Playground shapes.

All objects do respond to #= and #~=, however:

charlie = teresa.

simon = simon.

simon ~= charlie.


Here we are testing to see whether the two shapes are (or aren't) the same object.

Tip: by default, the #= message does compare two objects to see if they are one and the same (identical). However, you'll also see that it is possible to change the meaning of a message such that, in the case of shapes, #= could compare the shape areas instead.