Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use question mark operator when calling method on possible null value?

Tags:

dart

I have a varible containing an object which might be null. When trying to call a method I have to check for null. I want the result to be false if the variable is null. What is considered good and readable style to to this?

e.g.

class MyClass {
  bool boolMethod() {
    return true;
  }
}

void main() {
  MyClass mc = new MyClass();
  MyClass mcnull = null;

  bool val1 = mc?.boolMethod();
  bool val1null = mcnull?.boolMethod();

  bool val2 = mc != null && mc.boolMethod();
  bool val2null = mcnull != null && mcnull.boolMethod();
}

Especially when used in if-statements I consider the first version much more readable:

if (mc?.boolMethod())...

versus

if (mc != null && mc.boolMethod())...

But IntelliJ gives me the hint The value of the '?.' operator can be 'null' which isn't appropriate as an operand of a locaical operator. (null_aware_in_logical_operator). Ok - this is right because when the variable is null then I use the null as a boolean value. But it's ok in my case and I try to avoid suppressing warnings.

What is the suggested way? Other ideas?

like image 264
dsteinkopf Avatar asked Jan 29 '23 08:01

dsteinkopf


1 Answers

I think a common pattern is

  bool val1 = (mc?.boolMethod() ?? false);

The parens aren't required here but if such expressions are embedded into more complex expressions they are often necessary to get the expected behavior because of the low priority of ??

like image 166
Günter Zöchbauer Avatar answered Feb 01 '23 18:02

Günter Zöchbauer