ballerina-lang
ballerina-lang copied to clipboard
Type Narrowing doesnt work with match Statement
Consider the following code
import ballerina/io;
type UnaryExpr record {|
string operand;
|};
type TypeCastExpr record {|
string oprd;
|};
type Expr UnaryExpr|TypeCastExpr;
function foo(Expr expr) {
match expr {
var {oprd: o} => {
TypeCastExpr c = expr;
io:println(c);
}
}
}
public function main() {
Expr x = {oprd : "DFD"};
foo(x);
}
This code gives the following error.
incompatible types: expected 'TypeCastExpr', found 'Expr'
The same thing which is explained in this issue happens for the below example.
type UnaryExpr record {|
string oprd;
|};
public type TypeCastExpr record {|
string operand;
int td;
|};
type Expr UnaryExpr|TypeCastExpr;
function foo(Expr expr) {
match expr {
var { operand, td } => {
TypeCastExpr c = expr;
io:println(c);
}
}
}
public function main() {
Expr x = { operand: "BB", td: 2 };
foo(x);
}
@KavinduZoysa, this was fixed for beta4. Doesn't the sample you shared work on the current master with the changes in https://github.com/ballerina-platform/ballerina-lang/pull/32017? Seems to work for me.
The fix will be reverted with https://github.com/ballerina-platform/ballerina-lang/pull/33337. We will fix the issue when we deal with the related spec issue https://github.com/ballerina-platform/ballerina-spec/issues/827