Optional values, flattened and summed
The complete source of collectionTypes_optional.ek9, compiled by the EK9 compiler. Shown on collectionTypes.html.
#!ek9 defines module site.collectionTypes.optional defines program ShowOptionalType() stdout <- Stdout() //Example with a fully qualified declaration maybeInteger as Optional of Integer: Optional() of Integer //Nothing will be output cat maybeInteger > stdout //A type inferred declaration item1 <- Optional(5) cat item1 > stdout //two different ways of checking if optional has a value require item1.iterator().hasNext() require item1? //read as List of (Optional of Integer) //fully qualified declaration emptyOptionals as List of Optional of Integer: List() of Optional of Integer require emptyOptionals is empty //type inference mechanism - much more terse aListOfOptionals <- List(maybeInteger) aListOfOptionals += item1 aListOfOptionals += Optional(14) //But could have been defined like this someOptionals <- [maybeInteger, item1, Optional(14)] require length someOptionals == 3 //Use of flatten to get the items out of the optional cat aListOfOptionals | flatten > stdout //Calculate the sum of the integers. sum <- cat aListOfOptionals | flatten | collect as Integer require sum == 19 //Also possible to use an iterator if you wish while iter <- item1.iterator() then iter? stdout.println(`Value [${iter.next()}]`)
Download collectionTypes_optional.ek9
Output
5 5 14 Value [5]