import ballerina/io;

// Defines a class called `File`.
class File {
    string path;
    string contents;
    // `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);
    }
}

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);
}

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 {
    string path;
    string contents;

Defines a class called File.

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

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");
    io:println(f.contents);
}

new returns the newly constructed File object.

bal run init_return_type.bal
Hello World