Skip to main content
The is! operator is a binary type test operator used to assert that an object is not an instance of a specified type or any of its subtypes. It evaluates to a bool, returning true if the runtime type of the left-hand operand is incompatible with the type specified on the right-hand side.

Syntax

expression is! Type
  • expression: The variable or expression whose runtime type is being evaluated.
  • Type: The data type (class, mixin, enum, or interface) being checked against.

Operational Semantics

The operator compares the runtime type of the expression against Type adhering to Dart’s type hierarchy rules.
  1. Subtype Check: If the runtime type of expression is a subtype of Type (including Type itself), the operator evaluates to false.
  2. Incompatibility: If the runtime type of expression is not a subtype of Type, the operator evaluates to true.

Logical Equivalence

The is! operator serves as syntactic sugar for the logical negation of the is operator. It improves readability by eliminating the need for parentheses around the type check.
// The following expressions are semantically identical:
if (variable is! String) { ... }

if (!(variable is String)) { ... }

Nullability Rules

The evaluation of is! differs based on the nullability of the target Type.
  • Non-nullable Target (T): null is not an instance of a non-nullable type. Therefore, null is! T evaluates to true.
  • Nullable Target (T?): null is a valid instance of a nullable type. Therefore, null is! T? evaluates to false.

Evaluation Examples

The following code demonstrates the operator’s logic against inheritance hierarchies and null values:
void main() {
  Object value = 123; // Runtime type is int
  var empty = null;

  // --- Type Hierarchy Checks 
  
  // true: int is not a String
  print(value is! String); 

  // false: int is an int
  print(value is! int);    

  // false: int is a subtype of num
  print(value is! num);    

  // --- Nullability Checks 

  // true: null is not a non-nullable int
  print(empty is! int);  

  // false: null is a valid nullable int (int?)
  print(empty is! int?); 
}
Master Dart with Deep Grasping Methodology!Learn More