Search code examples
ballerinaballerina-swan-lake

How to create empty table in Ballerina and to add the records gradually


I need to create an empty and add records gradually to the created table. How can I do that with Ballerina? What are the possible functions which are applicable to a table in Ballerina?

Here is my record

type Employee record {|
    readonly string name;
    string department;
|};

Solution

  • You can create an empty table using an empty table constructor with no members. You can use the add or put functions from the table langlib to add members.

    type Employee record {|
        readonly string name;
        string department;
    |};
    
    public function main() {
        table<Employee> key(name) tb = table [];
    
        tb.add({name: "Emma", department: "IT"});
    }
    

    add panics if there is already a member with the specified key whereas put replaces the member.

    See API docs for the table langlib for all functions.