Search code examples
mappingballerinaballerina-swan-lake

Concatenating two maps using spread operator gives error in ballerina


I have tried to concatenate two maps using the spread operator, and it gives an error.

import ballerina/io;

map<string> map1 = {
    "key1": "value1"
};

map<string> map2 = {
    "key2": "value2"
};

public function main() {
    map<string> map3 = {...map1, ...map2};
    io:println(map3);
}

Error message: invalid usage of mapping constructor expression: multiple spread fields of inclusive mapping types are not allowed

What I'm doing wrong here?


Solution

  • This isn't allowed because the same field may be specified in both mappings. Basically, we can't use the spread field with more than one open mapping. Even when one is open, it has to have never-typed optional fields https://ballerina.io/learn/by-example/never-type/ for all of the fields that may be specified via other spread fields in order to ensure there will be no duplicates.

    For example, the following will work.

    import ballerina/io;
    
    record {| 
        string key1;
    |} map1 = {
        key1: "value1"
    };
    
    record {|
        never key1?;
        string...;
    |} map2 = {
        "key2": "value2"
    };
    
    public function main() {
        map<string> map3 = {...map1, ...map2};
        io:println(map3);
    }