withInstance<U, R> method
void
withInstance<U, R>(
- U value,
- void process(
- T value
- void otherwise(
- 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);
}
}