applyIfLazy method

T applyIfLazy(
  1. bool predicate(
    1. T value
    ),
  2. T block(
    1. T value
    )
)

Conditionally transforms this value based on a lazy predicate.

Evaluates the predicate with this value. If it returns true, applies the block transformation and returns the result. Otherwise, returns this value unchanged.

Use this when the condition depends on properties of the value itself, avoiding the need to compute the condition before calling the method.

Example:

final builder = StringBuilder('Hello')
  .applyIfLazy(
    (sb) => sb.length < 100,
    (sb) => sb.append(' World!'),
  );
// Appends only if current length is less than 100

Another example with configuration:

final settings = Settings(maxRetries: 3)
  .applyIfLazy(
    (s) => s.maxRetries < 5,
    (s) => s.copyWith(maxRetries: 5, enableBackoff: true),
  );

Implementation

T applyIfLazy(bool Function(T value) predicate, T Function(T value) block) {
  if (predicate(this)) {
    return block(this);
  }

  return this;
}