prefer_from_predicate
This rule flags a conditional whose branches are Option.of(value) and a None, where the condition tests that same value.
Why use this rule
Section titled “Why use this rule”Option.fromPredicate(value, test) is the one-expression form of exactly this shape, and it says what the code means: this value, if it passes this test.
The conditional also names the value twice — once in the condition and once inside the Some. That duplication is where the bug lives, and unlike a type error it compiles: a conditional that tests age but wraps otherAge reads as perfectly ordinary.
See also: fpdart: Option.fromPredicate
final option = age > 18 ? Option.of(age) : Option<int>.none();final option = Option.fromPredicate(age, (a) => a > 18);Either.fromPredicate is the equivalent when the rejected case needs to carry a failure:
Either.fromPredicate(age, (a) => a > 18, (a) => TooYoungFailure(a));Quick fix
Section titled “Quick fix”A quick fix rewrites the conditional, substituting the lambda’s parameter for the value throughout the condition — age > 18 becomes (a) => a > 18, not (_) => age > 18. That substitution is the point: fromPredicate is worth reaching for because the predicate reads as a test on the value, which a closure over the original variable does not.
The parameter name is checked against every identifier in the expression first, so it can never shadow something the condition already reads.
Known limitations
Section titled “Known limitations”A null test (value != null ? ... : none()) is left to prefer_from_nullable, whose fix produces better code for that shape.
By default only single-condition guards are reported. A three-clause condition often reads better as a conditional than folded into a lambda — raise max_condition_complexity if your project disagrees.
When the condition tests something other than the wrapped value, the conditional is not a predicate at all and is never reported.
Options
Section titled “Options”many_lints: rules: prefer_from_predicate: max_condition_complexity: 3rules: prefer_from_predicate: max_condition_complexity: 3| Option | Type | Default | Description |
|---|---|---|---|
max_condition_complexity |
int | 1 |
How many boolean operators the condition may contain and still be reported |
Configuration
Section titled “Configuration”This rule is in the opinionated preset. With a lower preset, enable it by
name with prefer_from_predicate: true.
To turn it off:
rules: prefer_from_predicate: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_unnecessary_option— An Option that is wrapped and immediately unwrapped earns nothing.prefer_from_nullable— A null check that builds an Option by hand is what Option.fromNullable is for.avoid_ad_hoc_left_type— A pipeline only composes when every step shares one error type.avoid_bare_await_in_do— Awaiting a raw Future inside a Do block escapes the block’s tracking.