Argument type inference shortcut

The Gosu parser provides additional type inference in a common case. If a block is defined within a method call parameter list, Gosu can infer the type of the block’s arguments from the parameter argument. You do not need to explicitly specify the argument type in this case.

In other words, if you pass a block to a method, in some cases Gosu can infer the type so you can omit the type for more concise code. This behavior is particularly relevant for using collection-related code that takes blocks as arguments.

For example, suppose you have this code:

var x = new ArrayList<String>(){"a", "b", "c"}

var y = x.map( \ str : String -> str.length )

You can omit the argument type (String). The map method signature allows Gosu to infer the argument type in the block from the definition of the map method.

You can use the more concise code:

var x = new ArrayList<String>(){"a", "b", "c"}

var y = x.map( \ str -> str.length )

The list method map is a built-in list enhancement method that takes a block with one argument. That argument is always the same as the type of the list. Therefore, Gosu infers that str must be of type String. You do not need to explicitly define either the type of the arguments or the return type.

The map method is implemented using a built-in Gosu enhancement of the Java language List interface.

See also