Type comparison in Ballerina and ‘typeof’ operator.

I am not going do a detailed explanation on purpose of Ballerina Language here with this article. If you would like to explore more please do visit Ballerina Language site. [1]

Any programming language has elements of comparing types of variables in language built in type system. If you are familiar with java language, you probably have come across, type comparison using Class objects and ‘instanceof’ operator in java. See [2] which has a good summary of type comparison in java. This also introduces basics type comparison semantics of programming languages.

The need for type comparison for Ballerina language came along with the introduction of ‘any’ typed variable support for Ballerina. Basically with this support, one can assign a value of any data type in Ballerina to an ‘any’ typed variable. The actual type of ‘any’ typed variable is available at runtime. So we cannot really make any guesses, on the type of the value which any typed variable holds beforehand, at compilation time. At different points of runtime execution ‘any’ typed variable may hold different types of values, so it’s beneficial to know the actual type of value ‘any’ typed variable holds at given point of time, to execute some custom logic based on some comparison on type of value. If you are interested in more details on ‘any’ typed variable support please visit [3] which describes more deep into this topic.

Basically there are two cases when considering type comparison for expressions in Ballerina.

  1. Detect if two expressions point to the same type.
type type_1 = typeof exp_1;
type type_2 = typeof exp_2;
if ( type_1 == type_2 ) {
// do then logic
}

2. Detect if one expression points to a given / known Ballerina type.

type type_1 = typeof exp_1;
if ( type_1 == typeof int ) {
// do then logic
}

Here we basically check whether, exp_1 gets evaluated to a value of int — Ballerina built in value type. Here ‘int’ is given / known type at the time we do the comparison. For the previous case basically, we do not know the types which exp_1 and exp_2 are evaluated to, the only information we do have is whether those two evaluated types are equal or not for the two expressions.

Basically in summary, Ballerina has this ‘typeof’ unary operator, which can be operated on, any ballerina expression and built in ( Eg:- int, string etc ) and user defined type ( Eg:- Struct ) names, operator will return the associated type which above those represent, and that can be used make comparisons as above.

Here is a working sample of ‘typeof’ operator, which can be found as a Ballerina by example. [4]

[1] https://ballerinalang.org/

[2] https://mostlymagic.wordpress.com/2013/10/25/how-to-compare-types-in-java/

[3] https://medium.com/@lanka.vitharana/any-type-support-in-ballerina-d9651ac53695

[4] https://ballerinalang.org/docs/by-example/typeof