Swan Lake Beta3 is here.
import ballerina/io;

// Constants can be defined without the type.
// Then the type is inferred from the right hand side.
const MAX_VALUE = 1000;
const URL = "https://ballerina.io";

// The value for variable `msg` can only be assigned once.
final string msg = loadMessage();

public function main() {
    io:println(MAX_VALUE);
    io:println(URL);
    io:println(msg);
}

function loadMessage() returns string {
    return "Hello World";
}

Const and Final

const means immutable and known at compile-time. Its type is singleton: set containing single value. A variable or a class field can be declared as final, meaning it cannot be assigned to, after it has been initialized.

import ballerina/io;
const MAX_VALUE = 1000;
const URL = "https://ballerina.io";

Constants can be defined without the type. Then the type is inferred from the right hand side.

final string msg = loadMessage();

The value for variable msg can only be assigned once.

public function main() {
    io:println(MAX_VALUE);
    io:println(URL);
    io:println(msg);
}
function loadMessage() returns string {
    return "Hello World";
}
bal run const_and_final
1000
https://ballerina.io
Hello World
import ballerina/io;

// Constants can be defined without the type.
// Then the type is inferred from the right hand side.
const MAX_VALUE = 1000;
const URL = "https://ballerina.io";

// The value for variable `msg` can only be assigned once.
final string msg = loadMessage();

public function main() {
    io:println(MAX_VALUE);
    io:println(URL);
    io:println(msg);
}

function loadMessage() returns string {
    return "Hello World";
}

Const and Final

const means immutable and known at compile-time. Its type is singleton: set containing single value. A variable or a class field can be declared as final, meaning it cannot be assigned to, after it has been initialized.

import ballerina/io;
const MAX_VALUE = 1000;
const URL = "https://ballerina.io";

Constants can be defined without the type. Then the type is inferred from the right hand side.

final string msg = loadMessage();

The value for variable msg can only be assigned once.

public function main() {
    io:println(MAX_VALUE);
    io:println(URL);
    io:println(msg);
}
function loadMessage() returns string {
    return "Hello World";
}
bal run const_and_final
1000
https://ballerina.io
Hello World
Subscribe to the newsletter

In the creation of Ballerina, we were inspired by so many technologies. Thank you to all that have come before us (and forgive us if we missed one): Java, Go, C, C++, D, Rust, Haskell, Kotlin, Dart, TypeScript, JavaScript, Python, Perl, Flow, Swift, Elm, RelaxNG, NPM, Crates, Maven, Gradle, Kubernetes, Docker, Envoy, Markdown, GitHub and WSO2.

Cookie Policy

This website uses cookies so that we can provide you with the best user experience. Read our Cookie Policy to find out more.

If you wish to disable cookies you can do so from your browser.

I Understand