typestar

Conditionals in Smalltalk

No if statement: booleans take ifTrue:ifFalse: messages.

"No if statement: booleans take ifTrue:ifFalse: messages."
| paperLeft job |
paperLeft := 42.

paperLeft > 100
    ifTrue: [Transcript show: 'Run the full edition'; cr]
    ifFalse: [Transcript show: 'Proofs only today'; cr].

"The whole thing is an expression that answers a value."
job := paperLeft > 40
    ifTrue: ['chapbook']
    ifFalse: ['bookmark'].
Transcript show: 'Next up: ', job; cr.

(paperLeft between: 40 and: 50)
    ifTrue: [Transcript show: 'Order more stock'; cr].

How it works

  1. The condition object receives the branching message.
  2. Both branches are blocks; the chosen one runs.
  3. The whole send is an expression that answers a value.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
464
Tokens
67
Three-star pace
60 tpm

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

Type this snippet

Step 1 of 3 in Control flow, step 7 of 31 in Language basics.

← Previous Next →

Conditionals in other languages