Skip to content

Non null coalescing operator #2165

Closed
Closed
@hamishjohnson

Description

@hamishjohnson

I find myself having to write this type of code quite often when dealing with nullable values:

TypeX != null ? TypeY : null;

A quick example I found, in with firebase auth:

Future<UserClaims?> getClaims(User firebaseUser) async {
  final idTokenResult = await firebaseUser.getIdTokenResult();

  return idTokenResult.claims != null
      ? UserClaims.fromJson(idTokenResult.claims!)
      : null;
}

I thought it would be nice to have a non-null coalescing operator to deal with this type of scenario. So, opposed to the null coalescing operator, if it evaluates the item on the left to be null, it returns null. But if it evaluates the left side to be non-null, then it continues on and returns the right side. Perhaps it would look something like this:

TypeX !? TypeY

Or, with my example:

Future<UserClaims?> getClaims(User firebaseUser) async {
  final idTokenResult = await firebaseUser.getIdTokenResult();

  return idTokenResult.claims !? UserClaims.fromJson(idTokenResult.claims!)
}

n.b. ?! could also be the operator. For some reason, it looks better and feels nicer to type, though it's less clear

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problemsstate-duplicateThis issue or pull request already exists

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions