Control Structures in Ballerina

Ayesh Almeida
2 min readJan 4, 2022

--

Photo by Joshua Hoehne on Unsplash
Photo by Joshua Hoehne on Unsplash

Programming would be boring if there is no logic involved in it. In a programming language logic is expressed using Control Structures. Lets understand the basic control structures we could find in Ballerina.

`if` Statement

if statement will evaluate a boolean expression and based on the result, it will execute the next steps of the program.

if statement has a else block and it is optional. If you need to evaluate multiple conditions, you could also use else if block.

We have is operator which is similar to instanceof operator in Java. Even though Java instanceof operator works only with types Ballerina is operator can work with values as well.

And if we want to evaluate the negation of the expression described with is operator we could simply combine it with ! .

`match` Statement

In Ballerina we have match statement which is similar to switch statement in C. It only matches the value not the type. == is used to identify whether the left hand side matches the value being matched. And the default clause is defined using _.

We could use | to match multiple values at once.

`foreach` Statement

The foreach statement iterates over an iterable value, by binding a variable to each member of the iterable value in order.

foreach can also be used to iterate over values in a given range.

foreach works with string values as well and will iterate over each characters of the given string value.

`while` Statement

while statement allows a more flexible iteration.

break and continue statements can be used within the loop to alter the control flow.

Ballerina has language support for almost all the control structures which we could find in a general purpose programming language. With succinct nature of its syntax, Ballerina provides an elegant way to express logic in a program.

--

--

Ayesh Almeida
Ayesh Almeida

Written by Ayesh Almeida

A Tech Enthusiast who wants to build simple solutions for complex problems.

No responses yet