ballerina-lang icon indicating copy to clipboard operation
ballerina-lang copied to clipboard

Type Narrowing doesnt work with match Statement

Open gimantha opened this issue 4 years ago • 3 comments

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'

gimantha avatar Jul 19 '21 09:07 gimantha

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 avatar Oct 21 '21 02:10 KavinduZoysa

@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.

MaryamZi avatar Oct 21 '21 13:10 MaryamZi

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

gimantha avatar Oct 22 '21 06:10 gimantha