Search code examples
serviceballerina

Define function in a Ballerina service


Please check the below code.

import ballerina/http;

service / on new http:Listener(9091) {
    function getMessage() returns string {
        return "custom message";
    }
    resource function get greeting() returns string {
        return getMessage();
    }
}

Here we have defined a function called getMessage and we get an undefined error when the function is used.

How do we solve that?


Solution

  • We have to use self to refer to members of the object within the Ballerina object.

    import ballerina/http;
    
    service / on new http:Listener(9091) {
        function getMessage() returns string {
            return "custom message";
        }
        resource function get greeting() returns string {
            return self.getMessage(); // use self
        }
    }