Post

Inferring The Type of A Numeric Literal

A value written in a numeric literal always represents a specific type, which is determined by the literal itself. The type of a literal can be one of the basic types, such as int, float, or decimal.

For example, the literal 10 represents the integer value 10, and its basic type is int. However, in some contexts, the same literal 10 can also represent a floating-point value 10.0 or a decimal value 10. Depending on the context, the compiler determines the appropriate type of the literal to be used.

See following example,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import ballerina/io;

const int TEN = 10;

public function main() {

    int a1 = 10;
    float a2 = 10;
    decimal a3 = 10;

    TEN a4 = 10;
    float|decimal a5 = 10; // float

    var a6 = 10; // int
    var a7 = 10.0; // float

    io:println(a1 is int);
    io:println(a2 is float);
    io:println(a3 is decimal);
    io:println(a4 is TEN);
    io:println(a5 is float);
    io:println(a6 is int);
    io:println(a7 is float);
}
true
true
true
true
true
true
true
 bal version
Ballerina 2201.6.0 (Swan Lake Update 6)
// Partial Code. Change View  to see full code.
const int TEN = 10;
public function main() {
    int a1 = 10;
    float a2 = 10;
    decimal a3 = 10;
    TEN a4 = 10;
    float|decimal a5 = 10; // float
    var a6 = 10; // int
    var a7 = 10.0; // float
}
// Highlights Only. Change View  to see full code.
const int TEN = 10;
int a1 = 10;
float a2 = 10;
decimal a3 = 10;
TEN a4 = 10;
float|decimal a5 = 10; // float
var a6 = 10; // int
var a7 = 10.0; // float

Code Breakdown

  • Line 7: The basic type of the literal 10 is int.
  • Line 8: The basic type of the literal 10 is float.
  • Line 9: The basic type of the literal 10 is decimal.
  • Line 11: The basic type of the literal 10 is int.
  • Line 12: The basic type of the literal 10 is float.
  • Line 14: The basic type of the literal 10 is int.
  • Line 15: The basic type of the literal 10.0 is float.

Algorithm

When determining the type basic of a literal, following 3 steps algorithm is used.

Let’s see how this works with different examples . Please note that, after deciding the basic type of the literal, the precise type of a literal is applied by the type checking algorithm.

If image is not visible enough, please click here to view it.

Step 1 - Check Syntatic FormCheckLiteralEndswithf/F?FloatingPointHEXLiteral?Endswithd/D?FloatingPointLiteral?YesNoNoNoYesYesNofloatdecimalfloat,decimalint,float,decimalPossible CandidatesLoopNStep 2 - Check with Contextual TypeContextual TypeTIntersectionT & NT & NEmpty?AddCandidateHasNext?YesYesNoUpdatedCandidatesNoEmpty?Hasint?Step 3 : Calculate TypeErrorYesNoHasfloat?YesNoYesNointfloatdecimalintfloatdecimalintfloatdecimalany
Type checking Algorithm - Numeric Literal Type
Inferring The Type of A Numeric Literal - The Algorithm.

Navigation

Site Settings

Site Theme

Source Code Density