3

How do you get the type of a variable in Ballerina?

I know that boolean checks are possible such as these below:

import ballerina/io;

public function main() {
    any x = "This is a test";
    io:println(x is string); // Evaluates to true
    io:println(x is float); // Evaluates to false
}

In Python, we use type(variable) and get the type, in Java it is as follows:

String a = "test";
a.getClass().getName()

How do we do this in Ballerina? I've tried to look in the docs and the closest I can find is lang.typedesc.

Rahul P
  • 2,493
  • 2
  • 17
  • 31

1 Answers1

11

You can use the typeof expression for get the type of any variable in Ballerina.

import ballerina/io;

public function main() {
    var x = 5;
    io:println(typeof x);
}

Please refer to the "Typeof expression" section of the language specification below for more information.

https://ballerina.io/spec/lang/2019R3/#section_6.25

Chanaka Lakmal
  • 1,112
  • 9
  • 19