select” iterable operation on Ballerina tables

Manuri Amaya Perera
Ballerina Swan Lake Tech Blog
1 min readAug 13, 2018

In Ballerina programming language, we have these iterable operations that you can perform on iterable collections such as arrays, maps and tables. One of the iterable operations available on table type is select operation. Please don’t confuse this select iterable operation with the Ballerina JDBC client’s select operation. This is a different one!

Let me explain what select iterable operation does.

Assume you have a table constrained with “Person” type. Here is the Ballerina record type for “Person”.

type Person record {
int id,
float salary,
string name,
};

And you have another type “Salary”.

type Salary record {
int id,
float salary,
};

Also, you have following function which would output a “Salary” record given a “Person” record!

function getSalary(Person p) returns Salary {
Salary s = { id: p.id, salary: p.salary };
return s;
}

If you want to get a “Salary” table which contains a record for each “Person” in the Person table, you’d have to iterate the Person table and call the above function on each Person record and add it to a new table like below.

table<Salary> salaryTable;
foreach person in personTable {
_ = salaryTable.add(getSalary(person));
}

But wait! Ballerina provides a shortcut for this! That is select iterable operation.

You can simple do like follows.

table<Salary> salaries = dt.select(getSalary);

Saved a few lines of code, didn’t we?

For the people who want to copy paste a program and see it running, I have put the complete example below that you can simply run! Enjoy!

--

--

Manuri Amaya Perera
Ballerina Swan Lake Tech Blog

I am an Engineer at WSO2. Currently working in the Ballerina team. Mainly contributing to Ballerina data client area. My GitHub URL: https://github.com/manuri