Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 56 jvm languages The previous code defines a tuple of the odd integer numbers between 1 and 100 As you can see embedding a foreach clause that may also contain a when guard does this There can also be several foreach clauses as the next example shows It generates a collection of pairs of integers expressed as a tuple of tuples let pairs i 2 j 3 foreach i in odds when i 30 and i 50 foreach j in 10 20 when j 2 1 println pairs Golo also supports destructuring of its data types and collections let l list 1 2 3 4 let a b l let head second tail l let m map a 123 b 456 foreach key value in m entrySet In the two examples above a would be value 1 and b would be value 2 Similarly head second and tail would be respectively 1 2 and list 3 4 Destructuring is also useful when dealing with map entries and decomposes them as pairs of keys and values a Golo map literal yields a java util HashMap Higher Order Functions Like most recent programming languages Golo supports higher order functions This means that functions can accept functions as parameters and return functions Given a function declared in a module you can obtain a reference to it using the operator Once a reference has been assigned to a function value calls can be made to it as in the following example module Foo function hello println Hello function main args let f hello f prints Hello Of course direct function declarations can be made as in the following let f str println str f Hello prints Hello Also functions that consist of a single expression can be expressed using the shorthand notation let f str println str f Hello prints Hello Function references have methods that allow them to be manipulated mainly to perform operations such as partial application and composition The provided methods closely mimic those of the java lang invoke package APIs Lets look at the following example let add a b c a b c let times a b a b let add_ 1_ and_ 2 add insertArguments 0 1 2
You must have JavaScript enabled to view digital editions.