Dart Test Operators


Type test operators in Dart are used to check the type of an object at runtime. They allow you to determine whether an object is of a specific type and are especially useful when working with inheritance and polymorphism. Dart provides two main type test operators: is and is!.

Overview of Type Test Operators

  1. is Operator
  2. is! Operator

1. is Operator

  • Description: The is operator checks if an object is of a specified type. It returns true if the object is of the specified type or if it is a subclass of that type; otherwise, it returns false.

  • Usage: Commonly used to verify the type of an object before performing type-specific operations.

Example:

void main() { var value = 42; if (value is int) { print('$value is an integer'); // Output: 42 is an integer } else { print('$value is not an integer'); } }

In this example, the is operator checks if value is of type int, and since it is, the message is printed.

Type Promotion

When you use the is operator in a conditional statement, Dart automatically promotes the type of the variable within the scope of that statement. This means you can use the variable as the specified type after the check without needing to cast it.

Example:

void main() { var value = 42; if (value is int) { // 'value' is treated as an int here print('Double the value: ${value * 2}'); // Output: Double the value: 84 } }

2. is! Operator

  • Description: The is! operator checks if an object is not of a specified type. It returns true if the object is not of the specified type or if it is not a subclass of that type; otherwise, it returns false.

  • Usage: Useful for confirming that an object does not belong to a specific type before proceeding with operations that assume a different type.

Example:

void main() { var value = 'Hello'; if (value is! int) { print('$value is not an integer'); // Output: Hello is not an integer } }

In this case, the is! operator checks if value is not of type int, and since it is a String, the message is printed.

Use Cases

  • Type Checking: Use is to safely check and work with types, especially when dealing with dynamic types or interfaces.
  • Type Safety: Helps ensure that operations are performed on the correct type, reducing runtime errors.

Summary of Type Test Operators

OperatorDescriptionExample
isChecks if an object is of a specified typevalue is int (returns true if value is an int)
is!Checks if an object is not of a specified typevalue is! int (returns true if value is not an int)

Conclusion

Type test operators in Dart provide a powerful mechanism for runtime type checking, enhancing the language's type safety features. By using is and is!, developers can write more robust and error-free code, especially when working with dynamic types or polymorphic class hierarchies. Understanding these operators is crucial for effective type management in Dart applications.