Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 59 jvm languages union Figure Nothing Square sideLength Rectangle firstSideLength secondSideLength Circle radius With this definition a Figure can be of the Nothing Square Rectangle or Circle concrete type Each type can have immutable fields and a constructor Here is the creation of a tuple with several Figure instances let figures Figure Square 23 Figure Rectangle firstSideLength 10 secondSideLength 20 Figure Circle 30 Figure Nothing Given each concrete type of Figure methods are being provided to check whether an instance is of a given type f isSquare f isCircle and so on The following example illustrates how to use these methods It also introduces the match operator that iteratively evaluates several conditions with when then otherwise clauses and returns a value println figures map f match when f isRectangle then f firstSideLength f secondSideLength when f isSquare then f sideLength when f isCircle then f radius otherwise join n Golo collections provide functional idioms such as map to create a new collection by applying a function to its elements and join to produce a string by concatenating elements with a separator Running the code above prints the following text 23 10 20 30 It is also possible to test instances not just for their type but also for values false println Figure Square 23 isSquare 20 true println Figure Square 23 isSquare 23 Because we might be interested in only a subset of a union of type fields we can use the special Unknown get value to indicate that the value of certain fields is not useful for matching let figs Figure Rectangle 10 10 Figure Rectangle 10 30 Figure Rectangle 30 30 Figure Circle 20 let _ Unknown get
You must have JavaScript enabled to view digital editions.