What is a difference between these operators ?? and ?.

In Dart, ?? and ?. are two different operators with distinct purposes:

  1. ?? (Null Coalescing Operator): The ?? operator, also known as the null coalescing operator, is used to provide a default value when the left-hand side expression evaluates to null. It allows you to handle null values in a concise and expressive way.

Syntax:

expression1 ?? expression2
  • If expression1 is not null, the ?? operator returns expression1.
  • If expression1 is null, the ?? operator returns expression2.

Example:

int a; // a is null
int b = a ?? 10; // b will be assigned 10 since 'a' is null

In this example, b will be assigned the value 10 because a is null, and the null coalescing operator provides the default value 10.

  1. ?. (Conditional Access Operator): The ?. operator, also known as the conditional access operator, is used to access properties or call methods on an object that might be null. It allows you to safely access properties and methods without causing a null reference exception.

Syntax:

object?.property
object?.method()
  • If object is not null, the property or method is accessed normally.
  • If object is null, the ?. operator returns null without throwing an exception.

Example:

class Person {
  String name;
  void sayHello() {
    print('Hello, ${name ?? "Unknown"}!');
  }
}

void main() {
  Person person;
  person?.sayHello(); // No error, 'sayHello' is not called because 'person' is null.
}

In this example, the ?. operator ensures that the sayHello() method is not called if person is null, avoiding a null reference exception.

In summary, the ?? (Null Coalescing Operator) is used to provide a default value for a nullable expression, while the ?. (Conditional Access Operator) is used to safely access properties or call methods on an object that might be null, preventing null reference exceptions. Both operators are useful for working with nullable values and handling null cases more effectively.

error: Content is protected !!