Back to Examples

Mapping binding pattern

A mapping binding pattern matches a mapping value with its fields. A record type will be assigned to the mapping binding pattern if it successfully matches the value. Both the map and record types can be used in mapping binding patterns. Record destructuring in binding patterns can be used to refer to existing variables as a record, destructure the given value on the right-hand side, and assign the values to each individual variable of the record during the runtime. These binding patterns are especially helpful when dealing with queries and are useful when destructuring JSON values.

import ballerina/io;

type Person record {|
    int id;
    string fname;
    string lname;
|};

public function main() {
    // `_` is used to ignore the value of the `id` field.
    // The values of the `fname` and `lname` fields are bound to the `firstName` and
    // `lastName` variable names.
    Person {id: _, fname: firstName, lname: lastName} = getPerson();
    io:println(firstName + " " + lastName);

    // The `fname` and `lname` fields do not have explicitly defined variable names.
    // `{fname, lname}` is the same as `{fname: fname, lname: lname}`.
    // The `id` field is ignored as it is not bound to a variable.
    Person {fname, lname} = getPerson();
    io:println(fname + " " + lname);

    string givenName;
    string surname;

    // This destructures and assigns the values of the fields in the destructed record
    // to the variable references.
    // The values of the `fname` and `lname` fields are assigned to the `givenName` and
    // `surname` variables.
    {fname: givenName, lname: surname} = getPerson();
    io:println(givenName + " " + surname);
}

function getPerson() returns Person {
    Person person = {id: 1001, fname: "Anne", lname: "Frank"};
    return person;
}
$ bal run mapping_binding_pattern.balAnne FrankAnne FrankAnne Frank

Related links

PreviousRest binding pattern in list binding pattern
NextRest binding pattern in mapping binding pattern