str
在下面的代码中,我已正确缩小to的类型string
。然而,第二个+=
复合运算符给了我一个编译错误:
ERROR compound assignment not allowed with nullable operands
ERROR operator '+' not defined for 'string?' and 'string'
Run Code Online (Sandbox Code Playgroud)
看起来编译器意外地不再遵守类型缩小?我期望 的类型str
直到string
块结束,并且我在代码中没有看到任何问题。
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);
}
Run Code Online (Sandbox Code Playgroud)
我在用着:
$ bal version
Ballerina 2201.1.0 (Swan Lake Update 1)
Language specification 2022R2
Update Tool 1.3.9
Run Code Online (Sandbox Code Playgroud)
小智 8
这是因为一旦变量可能已被分配,类型缩小就不再适用。
例如,可以分配给()
,str
但此后str
不能是缩小类型。
string? str = "a";
if str is string {
str = ();
// Now not valid, `str` is no longer `string`.
str += "c";
}
Run Code Online (Sandbox Code Playgroud)
讨论了如果赋值属于缩小类型的值(例如原始示例中的值),是否可以继续缩小类型。但当时由于规范问题中讨论的原因决定不这样做。