Introduction to Blocks
Damien Cassou, Stéphane Ducasse and Luc Fabresse
http://stephane.ducasse.free.fr
Blocks
Blocks are:
- kind of anonymous methods
- also called (lexical) closures
- used everywhere in Pharo
- loops, conditionals, iterators, ...
- GUI frameworks, DSLs, ...
- at the heart of the system
- just introduced in Java 8.0
Block Definition
A block is defined by [ ]
Block Definition Does not Execute Code
- Executing code may signal an Error
- But, no error when defining a block
- a block definition does not execute its body
- a block definition freezes its body computation
Executing a Block
Executing a block is done explicitly through value
A Block with 1 Argument
A block can take arguments (just like methods)
[ ]
delimits the block
:x
is a block argument
x + 2
is the block body
value: 5
executes the block with 5 as argument
x
is 5 during the block execution
Block Execution Value
Block execution returns the value of the last expression
Blocks can be Stored
- A block can be stored in a variable
- A block can be evaluated multiple times
Defining a Block with 2 Arguments
Example:
:x :y
are block arguments
How to execute a block with two arguments?
Executing a Block with 2 Arguments
value: 5 value: 7
evaluates the block with 5 and 7
x
is 5 and y
is 7 during the block evaluation
A Block with Temporary Variables
Blocks can define temp. variables (just like methods)
| args |
defines a temporary variable named args
args
exists only during block evaluation
Returning from a Block Returns from the Method
When a return ^
is executed in a block, computation exits the method defining the block
A Design Advice
- Use blocks with 2 or 3 arguments maximum
- Define a class instead of a block for more arguments
- A block encapsulates only 1 computation
- it cannot define more facets (e.g., printing)
Summary on Blocks
- Kind of anonymous method
- Technically lexical closures
- Can be stored in variables and method arguments
- Basis of conditionals, loops and iterators (see companion lectures)
- Further readings: http://deepintopharo.org
/