Functions in Ballerina lang

Photo by Nihal Demirci on Unsplash

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.

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.

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

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

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.

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.

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.

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.

References

Hope this will be helpful.

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

Technical Writer | Tech Enthusiast | Open source contributor