September 23, 2023

Smalltalk Blocks


Here is another example of a Dialog class message.

Dialog request: 'Enter an amount'
       initialAnswer: '1000'
       onCancel: [Dialog warn: 'You must enter a valid number']

The message answer is '1000', or whatever input the user enters before pressing OK
or nil if user cancels

Dialogue box with output: Enter amount and 1000 in the field


The request:initialAnswer:onCancel message selector takes three arguments. The final argument [Dialog warn: 'You must enter a valid number'] is a block. Blocks are objects, instances of the class BlockClosure. If the user cancels the dialogue box, the code inside the block is executed. This occurs because the block is sent a value message from within the request:initialAnswer:onCancel method.


[Dialog warn: 'You must enter a valid number'] value

will produce this

Dialogue box with output: You must enter a valid number


Blocks are sometimes referred to as methods without a name and they are used to implement the concept of conditional selection or branching.

Next page » Branching

Previous page « Dialog class
































































Up to top of page