In the code below I have correctly narrowed the type of str
to string
. However the second +=
compound operator gives me a compilation error:
ERROR compound assignment not allowed with nullable operands
ERROR operator '+' not defined for 'string?' and 'string'
It looks like the compiler unexpectedly doesn't obey the type narrowing anymore? I'm expecting the type of str
to be string
until end of the block and I fail to see any problems in my code.
import ballerina/io;
public function main() {
string? str = "a";
if str is string {
str += "b";
// why the second append fails ?
// ERROR compound assignment not allowed with nullable operands
// ERROR operator '+' not defined for 'string?' and 'string'
// str += "c";
// one possible workaround
str = <string>str + "c";
}
io:println(str);
}
I'm using:
$ bal version
Ballerina 2201.1.0 (Swan Lake Update 1)
Language specification 2022R2
Update Tool 1.3.9