Functions in Ballerina lang

I love Ballerina functions since it gives more flexibility and super easy to do a task.

This will cover basics of Ballerina language functions and following is the basic structure of a function.

function add(int numOne, int numTwo) returns int {
return numOne + numTwo;
}

Let’s play with Ballerina functions.

Required parameters

In the above function numOne, numTwo are required parameters and you should use the function as follows.

import ballerina/io;function main() {
int sum = add(1, 3);
io:println(sum);
}

Important : In Ballerina you can swipe the required parameter using names as follows.

import ballerina/io;function main() {
int sum = add(numTwo = 1, numOne = 3);
io:println(sum);
}

Note : If you have more than two parameters and unnamed parameters are taken as in the order as follows.

import ballerina/io;function cal(int numOne, int numTwo, int numThree) returns int {
return numOne + numTwo - numThree ;
}
function main() {
int sum = cal(1, numThree = 3, numTwo = 2);
//
1st parameter is taken as numOne as in the order.
io:println(sum);
}

Optional Parameters

In Ballerina we can use optional parameters which should be default parameters as well where there should be a default value assigned as follows.

function discount(int value, float discount = 0.1) returns float {
returns value * discount;
}

Above function generate the discount for the given value and 2nd parameter is default since it is optional. If the second parameter is not provided then the default value is taken as follows.

import ballerina/io;function main() {
io:println(discount(100)); // 10
io:println(discount(100, 0.2)); // 20
}

Note : If you need you can swipe the parameters using names as well.

Return multiple values from a function

In ballerina you can return multiple values from a function using Tuple as follows.

import ballerina/io;// This function will return full name and age.
function info(string first, string last, int age)
returns [string, int] {
return [first.concat(" ", last), age];
}
function main() {
string fullName;
int age;

[fullName, age] = info("Yashod", "Perera", 25);
io:println(fullName); // Yashod Perera
io:println(age); // 25
}

Get either type from a function

In ballerina you can get either type from a function which means you can get either int or string, int or error etc.

import ballerina/io;function test(int a, int b) returns int|string {
if (a > b) {
return "A is bigger";
} else {
return b;
}
}
function main() {
io:println(test(10,12)); // 12
io:println(test(12,10)); // A is bigger
}

References

Hope this will be helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store