import ballerina/io;

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

public function main() {
    // key field, `name` is of `record` type.
    table<Employee> key(name) t = table [
        {name: {first: "John", last: "Smith"}, salary: 100},
        {name: {first: "Fred", last: "Bloggs"}, salary: 200}
    ];

    Employee? e = t[{first: "Fred", last: "Bloggs"}];
    io:println(e);
}

Structured keys

Key fields can be structured as long as they belong to any subtype of plain data. The value of the key field must be immutable. The initializer of the readonly field will be constructed as immutable. In other cases, can use cloneReadOnly() to create an immutable value.

import ballerina/io;
type Employee record {
    readonly record {
        string first;
        string last;
    } name;
    int salary;
};
public function main() {
    table<Employee> key(name) t = table [
        {name: {first: "John", last: "Smith"}, salary: 100},
        {name: {first: "Fred", last: "Bloggs"}, salary: 200}
    ];

key field, name is of record type.

    Employee? e = t[{first: "Fred", last: "Bloggs"}];
    io:println(e);
}
bal run structured_keys.bal
{"name":{"first":"Fred","last":"Bloggs"},"salary":200}