Overview of blocks
Gosu supports in-line functions that you can pass around as objects, which are called blocks. Other languages call blocks closures or lambda expressions.
Blocks are useful as method parameters, in which the method’s implementation generalizes a task or algorithm but callers provide code to implement the details of the task. For example, Gosu adds many useful methods to Java collections classes that take a block as a parameter. That block could return an expression, such as a condition against which to test each item, or could represent an action to perform on each item.
For example, the following Gosu code makes
a list of strings, sorts the list by String
length, and then iterates across the result list to print each item in
order:
var strings = { "aa", "ddddd", "c" }
strings.sortBy(\ str -> str.length).each(\ str -> { print(str) })
Block shortcut for one-method interfaces
If an anonymous inner class implements an interface that has exactly one method, you can use a Gosu block to implement the interface. The Gosu block is an alternative to using an explicit anonymous class. You can use a Gosu block for interfaces that are defined in either Gosu or Java. For example:
_callbackHandler.execute(\ -> { /* Your Gosu statements here */ })See also
