Skip to content

Commit a0c0036

Browse files
jzheauxsbrannen
authored andcommitted
Introduce Converter.andThen(...)
Closes gh-23379
1 parent 8057fb3 commit a0c0036

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

spring-core/src/main/java/org/springframework/core/convert/converter/Converter.java

+18
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.core.convert.converter;
1818

1919
import org.springframework.lang.Nullable;
20+
import org.springframework.util.Assert;
2021

2122
/**
2223
* A converter converts a source object of type {@code S} to a target of type {@code T}.
@@ -26,6 +27,7 @@
2627
* <p>Implementations may additionally implement {@link ConditionalConverter}.
2728
*
2829
* @author Keith Donald
30+
* @author Josh Cummings
2931
* @since 3.0
3032
* @param <S> the source type
3133
* @param <T> the target type
@@ -42,4 +44,20 @@ public interface Converter<S, T> {
4244
@Nullable
4345
T convert(S source);
4446

47+
/**
48+
* Construct a composed {@link Converter} that first applies this {@link Converter} to
49+
* its input, and then applies the {@code after} {@link Converter} to the result.
50+
*
51+
* @since 5.2
52+
* @param <U> the type of output of both the {@code after} {@link Converter} and the
53+
* composed {@link Converter}
54+
* @param after the {@link Converter} to apply after this {@link Converter}
55+
* is applied
56+
* @return a composed {@link Converter} that first applies this {@link Converter} and then
57+
* applies the {@code after} {@link Converter}
58+
*/
59+
default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
60+
Assert.notNull(after, "after cannot be null");
61+
return (S s) -> after.convert(convert(s));
62+
}
4563
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.springframework.core.convert.converter;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.assertj.core.api.Assertions.assertThat;
6+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
7+
8+
/**
9+
* Tests for {@link Converter}
10+
*
11+
* @author Josh Cummings
12+
*/
13+
public class ConverterTests {
14+
Converter<Integer, Integer> moduloTwo = number -> number % 2;
15+
16+
@Test
17+
public void andThenWhenGivenANullConverterThenThrowsException() {
18+
assertThatExceptionOfType(IllegalArgumentException.class)
19+
.isThrownBy(() -> this.moduloTwo.andThen(null));
20+
}
21+
22+
@Test
23+
public void andThenWhenGivenConverterThenComposesInOrder() {
24+
Converter<Integer, Integer> addOne = number-> number + 1;
25+
assertThat(this.moduloTwo.andThen(addOne).convert(13)).isEqualTo(2);
26+
assertThat(addOne.andThen(this.moduloTwo).convert(13)).isEqualTo(0);
27+
}
28+
}

0 commit comments

Comments
 (0)