import ballerina/io;

type Employee record {
    readonly string name;
    int salary;
};

// Creates a `table` with `Employee` type members, where each
// member is uniquely identified using their `name` field.
table<Employee> key(name) t = table [
    { name: "John", salary: 100 },
    { name: "Jane", salary: 200 }
];

function increaseSalary(int n) {
    // Iterates over the rows of `t` in the specified order.
    foreach Employee e in t {
        e.salary += n;
    }
}

public function main() {
    // Retrieves `Employee` with key value `Fred`.
    Employee? e = t["Fred"];

    increaseSalary(100);
    io:println(t);
}

Table Syntax

A record field can be declared as readonly: cannot assign to the field after the record is created. table type gives type of row and name of key field. table constructor expression looks like an array constructor. foreach statement will iterate over a table’s rows in order. Use t[k] to access a row using its key.

import ballerina/io;
type Employee record {
    readonly string name;
    int salary;
};
table<Employee> key(name) t = table [
    { name: "John", salary: 100 },
    { name: "Jane", salary: 200 }
];

Creates a table with Employee type members, where each member is uniquely identified using their name field.

function increaseSalary(int n) {
    foreach Employee e in t {
        e.salary += n;
    }
}

Iterates over the rows of t in the specified order.

public function main() {
    Employee? e = t["Fred"];

Retrieves Employee with key value Fred.

    increaseSalary(100);
    io:println(t);
}
bal run table_syntax.bal
[{"name":"John","salary":200},{"name":"Jane","salary":300}]