typestar

Copying and identity in Smalltalk

= asks equal contents; == asks same object.

"= asks equal contents; == asks same object; copy splits them."
| tray duplicate alias |
tray := OrderedCollection new.
tray add: 'em quad'.

alias := tray.
duplicate := tray copy.

duplicate add: 'en quad'.
Transcript show: 'Original: ', tray size printString; cr.
Transcript show: 'Copy: ', duplicate size printString; cr.

Transcript show: (alias == tray) printString; cr.
Transcript show: (duplicate = tray) printString; cr.
Transcript show: (duplicate == tray) printString; cr.

How it works

  1. An alias is the same object; a copy is a new one.
  2. Growing the copy leaves the original untouched.
  3. == distinguishes what = cannot.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
482
Tokens
79
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 3 of 3 in Order & identity, step 23 of 31 in Language basics.

← Previous Next →