Friday 30 October 2015

Blocks - OO Computing with Smalltalk Ch 23.4

A Block object is created by enclosing any expression, or expression series, in square brackets.

The block can be thought of being just like a method, but without a name.

Blocks can be assigned to variables.

A block can have arguments, just like a method, and they get called block arguments.

They are declared inside the block, at the start, with a preceding colon, and a | at the end of the list of block arguments.

e.g.

    aBlock := [ :blockArgument1 :blockArgument2 | "and the meat of the block goes here." ]  

To evaluate a block with a single block argument, you send it the message value:
To evaluate a block with two block arguments, you send it the message value:value:
To evaluate a block with three block arguments, you send it the message value:value:value:

To evaluate a block with more than three arguments, you send it the message valueWithArguments: with the arguments in an array as the message argument.

Blocks can have temporary variables, declared between | | immediately after the block arguments are declared.

Methods return either self or the explicit ^ return,

Blocks return either the result of evaluating the last expression in the block, or the first explicit ^ return they encounter.



 

e.g. t

No comments:

Post a Comment