Skip to content

Commit cc4b4b6

Browse files
frecco75Fabien Recco
andauthored
Add peekError on Validation (#2649)
Co-authored-by: Fabien Recco <[email protected]>
1 parent 502e95e commit cc4b4b6

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/main/java/io/vavr/control/Validation.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -807,6 +807,15 @@ public final Validation<E, T> peek(Consumer<? super T> action) {
807807
return this;
808808
}
809809

810+
public final Validation<E, T> peekError(Consumer<? super E> action) {
811+
Objects.requireNonNull(action, "action is null");
812+
813+
if (isInvalid()) {
814+
action.accept(getError());
815+
}
816+
return this;
817+
}
818+
810819
/**
811820
* A {@code Validation}'s value is computed synchronously.
812821
*

src/test/java/io/vavr/control/ValidationTest.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,26 @@ public void shouldFlatMapInvalid() {
224224
assertThat(invalid.flatMap(v -> Validation.valid("ok"))).isSameAs(invalid);
225225
}
226226

227+
// -- peekError
228+
229+
@Test
230+
public void shouldPeekErrorNil() {
231+
assertThat(empty().peekError(t -> {})).isEqualTo(empty());
232+
}
233+
234+
@Test
235+
public void shouldPeekErrorForInvalid() {
236+
final int[] effect = { 0 };
237+
final Validation<Integer, ?> actual = Validation.invalid(1).peekError(i -> effect[0] = i);
238+
assertThat(actual).isEqualTo(Validation.invalid(1));
239+
assertThat(effect[0]).isEqualTo(1);
240+
}
241+
242+
@Test
243+
public void shouldNotPeekErrorForValid() {
244+
Validation.valid(1).peekError(i -> { throw new IllegalStateException(); });
245+
}
246+
227247
// -- orElse
228248

229249
@Test

0 commit comments

Comments
 (0)