import ballerina/io;

// Defines a `class` called `File`.
class File {

    string path;
    string contents;
    // The `init()` method is used to initialize the `object`.
    // when creating a new `object`.
    function init(string p, string? c) returns error? {
        self.path = p;
        self.contents = check c.ensureType(string);
        return;
    }

}

public function main() returns error? {
    // `new` returns the newly-constructed `File` object.
    File f = check new File("test.txt", "Hello World");

    io:println(f.contents);
    return;
}

Init return type

init function has a return type, which must be a subtype of error?. If init returns (), then new returns the newly constructed object. If init returns an error, then new returns that error. If init does not specify a return type, then the return type defaults to () as usual, meaning that new will never return an error.

import ballerina/io;
class File {

Defines a class called File.

    string path;
    string contents;
    function init(string p, string? c) returns error? {
        self.path = p;
        self.contents = check c.ensureType(string);
        return;
    }

The init() method is used to initialize the object. when creating a new object.

}
public function main() returns error? {
    File f = check new File("test.txt", "Hello World");

new returns the newly-constructed File object.

    io:println(f.contents);
    return;
}
bal run init_return_type.bal
Hello World