I have tried a sample Ballerina code below.
type RecordSample record {|
int x;
|};
class testClass {
RecordSample|error sampleVariable;
function init() {
self.sampleVariable = test();
}
function methodA() {
self.init()
if self.sampleVariable is error {
return self.sampleVariable.message();
}
}
}
function test() returns RecordSample|error {
if 1> 2 {
return {x: 1};
} else {
return error("Error");
}
}
I am getting an error as it do not Narrow type in line self.sampleVariable.message(); May i know the reason for this error ? (Error Message is undefined function 'message' in type )
Type is narrowed only for local variables and parameters - basically, where it can be guaranteed that the narrowed type will hold. Assigning to a local variable and doing the is
check will narrow the type of the variable.
RecordSample|error sampleVariable = self.sampleVariable;
if sampleVariable is error {
return sampleVariable.message();
}