import ballerina/io;

//`var` says that the type of the variable is from the type of expression
// used to initialize it.
var x = "str";

function printLines(string[] sv) {
    // Type inference with a `foreach` statement.
    foreach var s in sv {
        io:println(s);
    }

}

public function main() {
    string[] s = [x, x];
    printLines(s);

    // Infers `x`'s type as `MyClass`.
    var x = new MyClass();
    MyClass _ = x;

    // Infers the class for `new` as `MyClass`.
    MyClass _ = new;

}

class MyClass {
    function foo() {

    }
}

Type inference

Type inference is local and restricted to a single expression. Overuse of type inference can make the code harder to understand.

import ballerina/io;
var x = "str";

var says that the type of the variable is from the type of expression used to initialize it.

function printLines(string[] sv) {
    foreach var s in sv {
        io:println(s);
    }

Type inference with a foreach statement.

}
public function main() {
    string[] s = [x, x];
    printLines(s);
    var x = new MyClass();
    MyClass _ = x;

Infers x’s type as MyClass.

    MyClass _ = new;

Infers the class for new as MyClass.

}
class MyClass {
    function foo() {
    }
}
bal run type_inference.bal
str
str