import ballerina/io;

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

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

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

    // Infer x as type MyClass
    var x = new MyClass();

    // Infer class for new as MyClass
    MyClass y = new;
}

class MyClass {
    function foo() {

    }
}

Type Inference

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

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

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

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

Type inference with foreach statement

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

Infer x as type MyClass

    MyClass y = new;
}

Infer class for new as MyClass

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