Category:Smalltalk: Difference between revisions
Content added Content deleted
Line 500: | Line 500: | ||
it should be noted that a "ˆ" (return) inside a block will return from the enclosing method, NOT only from the block. And that this is an essential semantic property of the return (technically, it may be a long return from a deeply nested call hierarchy, possibly involving unwind actions). |
it should be noted that a "ˆ" (return) inside a block will return from the enclosing method, NOT only from the block. And that this is an essential semantic property of the return (technically, it may be a long return from a deeply nested call hierarchy, possibly involving unwind actions). |
||
This makes it possible to pass a block to eg. collections to enumerate elements up-to and until some condition is met. For example, if we need a helper method, which |
This makes it possible to pass a block to eg. collections to enumerate elements up-to and until some condition is met. For example, if we need a helper method, which searches the first element in a dataset to some condition and evaluate an action on it, we can write: |
||
<lang smalltalk>findSomeElementWhichMeetsCondition:conditionBlock thenDo:actionBlock ifNone:failBlock |
<lang smalltalk>findSomeElementWhichMeetsCondition:conditionBlock thenDo:actionBlock ifNone:failBlock |
||
dataSet do:[:eachElement | |
dataSet do:[:eachElement | |
||
Line 509: | Line 509: | ||
^ failBlock value</lang> |
^ failBlock value</lang> |
||
Here, a block is passed to the dataSet's "do:" method, which will return (if invoked inside the "do:") from the containing findSomeElement method. |
Here, a block is passed to the dataSet's "do:" method, which will return (if invoked inside the "do:") from the containing findSomeElement method. |
||
The above can be used as: |
|||
⚫ | |||
<lang smalltalk>myDataSet |
|||
findSomeElementWhichMeetsCondition:[:record | record name = 'John'] |
|||
thenDo:[:record | record print ] |
|||
ifNone:[ 'nothing found' print ]</lang> |
|||
⚫ | |||
There are rare situations, where an explicit block return is needed (for example, to break out of a loop in the middle, without returning from the method). For this, block provides a special "valueWithExit" method, so you can write: |
There are rare situations, where an explicit block return is needed (for example, to break out of a loop in the middle, without returning from the method). For this, block provides a special "valueWithExit" method, so you can write: |