Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Even after ensuring type, the compiler does not pick up the variable #42593

Closed
sacheeramesh opened this issue Apr 18, 2024 · 2 comments
Closed
Labels
Team/CompilerFE All issues related to Language implementation and Compiler, this exclude run times. Type/Question

Comments

@sacheeramesh
Copy link

sacheeramesh commented Apr 18, 2024

Description:
A record type has a nullable attribute, It can either be a string or a null. In the code, I checked the attribute is a string, but within the if condition, I cannot treat the variable as a string. the compiler still picks up the variable as a string or null.

Steps to reproduce:

Record type :

# Employee record.
type Employee record {
    # First name of the employee
    string firstName;
    # Compensation details or null
    string? compensation;
};

# Compensation record.
public type Compensation record {|
    # Compensation type
    string key;
    # Compensation value
    string value;
    # Type of the value
    CompensationType 'type;
|};

Code:

Employee|error result = databaseClient->queryRow(query);
 types:Compensation[]|error compensations = [];
    if result.compensation is string {
        compensations = result.compensation.fromJsonStringWithType();
    }

Error:
incompatible types: expected 'string', found 'string?'

Affected Versions:
Ballerina 2201.8.4
OS, DB, other environment details and versions:

Related Issues (optional):

Suggested Labels (optional):

Suggested Assignees (optional):

@MaryamZi MaryamZi transferred this issue from ballerina-platform/ballerina-library Apr 18, 2024
@MaryamZi MaryamZi added Type/Question Team/CompilerFE All issues related to Language implementation and Compiler, this exclude run times. and removed Type/Bug labels Apr 18, 2024
@MaryamZi
Copy link
Member

Type narrowing happens only for parameters and local variables. Since the record value is mutable, we can't guarantee that the field will continue to be a string even if the is check evaluates to true when that check is done.

You can assign result.compensation to a variable and use that instead, narrowing will then work as you expect here.

string? compensation = result.compensation;
if compensation is string {
    compensations = compensation.fromJsonStringWithType();
}

@sacheeramesh
Copy link
Author

HI @MaryamZi Understood and thank you for the update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Team/CompilerFE All issues related to Language implementation and Compiler, this exclude run times. Type/Question
Projects
None yet
Development

No branches or pull requests

2 participants