Skip to content

Local variable is not promoted when checked that its value is a non-null literal #1726

Open
@mateusfccp

Description

@mateusfccp

Consider the following code:

enum Fruit {apple, banana, orange}

void printFruitIfAppleElsePrintGarbage(Fruit? fruit) {  
  if (fruit == Fruit.apple) {
    printFruit(fruit);
  } else {
    print('🗑');
  }
}

void printFruit(Fruit fruit) => print(fruit);

The code above won't compile, even if it is (seemingly) clear that, if fruit is Fruit.apple it won't possibly be null. The same happens if using a switch-case. The following won't compile:

void printFruitIfAppleElsePrintGarbage(Fruit? fruit) {
  switch (fruit) {
    case Fruit.apple: return printFruit(fruit);
    default: return print('🗑');
  }
}

Obviously, if I explicitly check for null (if (fruit != null && fruit == Fruit.apple)) it will be properly promoted.

Is this the intended behavior? If yes, why? Maybe I am missing something and there's some technical reason to why the compiler can't be sure that the value is not null in these cases?

Metadata

Metadata

Assignees

No one assigned

    Labels

    flow-analysisDiscussions about possible future improvements to flow analysisrequestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions