Home > Net >  Is there a way to multiply a nullable with a compact operator, something like "?*"
Is there a way to multiply a nullable with a compact operator, something like "?*"

Time:08-25

Is there a way to get a multiplication with a nullable using a compact syntax such as:

int? i;

final j = i ?* 2 ?? null;

Rater than:


final j = i == null ? null : i! * 2;

CodePudding user response:

No. There is no null-aware syntax which extends to operators (other than [] and []=).

You can introduce an extension method doing multiplication, like:

extension IntOps on int {
  int imul(int other) => this * other;
  int iadd(int other) => this   other;
  int isub(int other) => this - other;
  // etc.
}

and then you can do:

int? i;
final j = i?.imul(2);
  • Related