diff --git a/examples/unions/unions.bal b/examples/unions/unions.bal index f175e35e4b..6170bbbfc6 100644 --- a/examples/unions/unions.bal +++ b/examples/unions/unions.bal @@ -19,14 +19,73 @@ public function main() { io:println(nameToString(name1)); io:println(nameToString(name2)); + + map grades1 = { + math: "80", + physics: (), + chemistry: "76" + }; + // Parsing a map with grade values that are either the string + // representation of an integer or nil results in a map of + // just the non-nil grades as integers. + map|error parseGrades1 = parseGrades(grades1); + io:println(parseGrades1); + + map grades2 = { + math: "80", + physics: "N/A", + chemistry: "76" + }; + // Attempting to parse a map with string values that + // are not the string representation of a number results + // in the function terminating early, returning the error. + map|error parseGrades2 = parseGrades(grades2); + io:println(parseGrades2); } function nameToString(Name nm) returns string { // Checks whether `nm` belongs to `string` type. if nm is string { - + // The type of `nm` is narrowed to `string` here. + // Therefore, you can directly return `nm` from this + // function that specifies `string` as the return type. return nm; } else { + // The type of `nm` is narrowed to `StructuredName` here. + // Therefore, you can directly access fields defined in + // the `StructuredName` record. return nm.firstName + " " + nm.lastName; } } + +function parseGrades(map grades) returns map|error { + map parsedGrades = {}; + + foreach [string, string|()] [subject, grade] in grades.entries() { + // If the `grade` value is `()`, continue on to the next entry. + if grade is () { + continue; + } + + // The type of `grade` is narrowed to `string` here + // since we won't reach here if the value is `()`, due + // to the `continue` statement above. + // Therefore, we can directly use `grade` where a `string` + // value is expected. + int|error parsedGrade = int:fromString(grade); + + // If the `parsedGrade` value is an error value, terminate the + // execution of this function and return the error value. + if parsedGrade is error { + return parsedGrade; + } + + // Since we return the error from the function if `parsedGrade` is `error`, + // the type of `parsedGrade` is narrowed to `int` here, + // allowing it to be used as an `int`-typed variable when adding + // the value to a map of integers. + parsedGrades[subject] = parsedGrade; + } + + return parsedGrades; +} diff --git a/examples/unions/unions.out b/examples/unions/unions.out index 5dd26515ff..128fed018f 100644 --- a/examples/unions/unions.out +++ b/examples/unions/unions.out @@ -1,3 +1,5 @@ $ bal run unions.bal Rowan Atkinson Leslie Banks +{"math":80,"chemistry":76} +error("{ballerina/lang.int}NumberParsingError",message="'string' value 'N/A' cannot be converted to 'int'")