Ballerina类型收窄问题:调用error的message()方法报错原因咨询
Ballerina类型收窄失效:调用error的
message()方法报错原因 示例代码
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"); } }
问题描述
在methodA方法中,先调用self.init(),随后通过if self.sampleVariable is error进行类型检查,但调用self.sampleVariable.message()时提示“undefined function 'message' in type”,类型未被收窄,请问报错原因是什么?
原因分析
这个报错的核心原因是Ballerina的类型检查器无法静态保证类成员变量sampleVariable在init()调用后到类型检查的这段时间内,没有被其他代码修改:
- 类的成员变量属于共享状态,类型检查器无法排除存在并发操作或后续代码修改该变量类型的可能性。
- Ballerina的类型收窄规则仅对局部变量生效,因为局部变量的生命周期完全由当前控制流掌控,不会被外部干扰,类型检查器可以安全确认其类型。而成员变量不具备这个特性,因此即使做了
is error的类型检查,类型检查器也不会对其进行类型收窄。
解决方法
将成员变量的值赋值给一个局部变量,再对局部变量进行类型检查,这样就能触发类型收窄:
function methodA() returns string? { self.init(); // 将成员变量赋值给局部变量 RecordSample|error temp = self.sampleVariable; if temp is error { return temp.message(); } return null; }
内容的提问来源于stack exchange,提问作者Thenusan Santhirakumar
相关产品推荐
相关产品推荐

