method that accepts a block and the block accepts

2019-09-17 15:49发布

How can I send a block and its argument to a method ? so the method receive the block and the block receives the argument and I run the block in the method iteslf...

2条回答
Juvenile、少年°
2楼-- · 2019-09-17 15:56

Just pass the block and its argument to the method as separate arguments. Then send #value: to the block to pass the argument to the block. E.g.

methodTaking: aBlock and: anArgument
  aBlock value: anArgument.
  ...
查看更多
神经病院院长
3楼-- · 2019-09-17 16:21

For an example have a look at the sort: method of OrderedCollection (you'll find the block evaluated finally in SortedCollection>>mergeFirst:middle:last:into:by:).
Inside a method that accepts a block as parameter, you would evaluate the block, this means call it with parameters and use the result. Not so much try to "access the argument of the block".

You would e.g. send a message with a block as parameter to a collection of colors to sort it by luminance:

colors := OrderedCollection new. 
colors addAll: { Color red. Color yellow. Color white. Color black }. 
colors sort: [:c1 :c2 | c1 luminance <= c2 luminance].

results in: "an OrderedCollection(Color black Color red Color yellow Color white)"

查看更多
登录 后发表回答