withInstance<U, R> method

void withInstance<U, R>(
  1. U value,
  2. void process(
    1. T value
    ), {
  3. void otherwise(
    1. U value
    )?,
})

Run process with value if value is assignable to this type.

otherwise can be provided and will be ran if value is not assignable to this type. This is similar to an if (instance is ...) { ... } else { ... } statement:

// Before
if (instance is String) {
  // Do something
} else {
  // Do something else
}

// After
stringType.withInstance(
  instance,
  (instance) {
    // Do something with instance, now promoted to a String
  },
  otherwise: (instance) {
    // Do something else
  },
);

Implementation

void withInstance<U, R>(
  U value,
  void Function(T value) process, {
  void Function(U value)? otherwise,
}) {
  if (value is T) {
    process(value);
  } else {
    if (otherwise == null) return;
    otherwise(value);
  }
}