ballerina-platform / ballerina-spec

Ballerina Language and Platform Specifications
Other
167 stars 53 forks source link

Proposal: Introduce match expressions #1314

Open Shadow-Devil opened 3 months ago

Shadow-Devil commented 3 months ago

Description: It would be great to have also match expressions, similar to match statements, where each branch has to return a value (of the same type), which can then be used. It would also be great to introduce a syntax that one can omit the curly braces if only a value is returned.

Example from here. Instead of

const KEY = "xyzzy";

function mtest(any v) returns string {

    match v {
        17 => {
            return "number";
        }
        true => {
            return " boolean";
        }
        "str" => {
            return "string";
        }
        KEY => {
            return "constant";
        }
        0|1 => {
            return "or";
        }
        _ => {
            return "any";
        }
    }
}

one could write:

const KEY = "xyzzy";

function mtest(any v) returns string {

    return match v {
        17 => "number";
        true => "boolean";
        "str" => "string";
        KEY => "constant";
        0|1 => "or";
        _ => "any";
    }
}

This idea is mainly coming from Java's switch expressions.

Suggested Labels:

Code sample that shows issue:

Related Issues: