Introduce Converter.andThen(...)
Closes gh-23379
This commit is contained in:
committed by
Sam Brannen
parent
8057fb38b2
commit
a0c00362c3
@@ -17,6 +17,7 @@
|
||||
package org.springframework.core.convert.converter;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* A converter converts a source object of type {@code S} to a target of type {@code T}.
|
||||
@@ -26,6 +27,7 @@ import org.springframework.lang.Nullable;
|
||||
* <p>Implementations may additionally implement {@link ConditionalConverter}.
|
||||
*
|
||||
* @author Keith Donald
|
||||
* @author Josh Cummings
|
||||
* @since 3.0
|
||||
* @param <S> the source type
|
||||
* @param <T> the target type
|
||||
@@ -42,4 +44,20 @@ public interface Converter<S, T> {
|
||||
@Nullable
|
||||
T convert(S source);
|
||||
|
||||
/**
|
||||
* Construct a composed {@link Converter} that first applies this {@link Converter} to
|
||||
* its input, and then applies the {@code after} {@link Converter} to the result.
|
||||
*
|
||||
* @since 5.2
|
||||
* @param <U> the type of output of both the {@code after} {@link Converter} and the
|
||||
* composed {@link Converter}
|
||||
* @param after the {@link Converter} to apply after this {@link Converter}
|
||||
* is applied
|
||||
* @return a composed {@link Converter} that first applies this {@link Converter} and then
|
||||
* applies the {@code after} {@link Converter}
|
||||
*/
|
||||
default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
|
||||
Assert.notNull(after, "after cannot be null");
|
||||
return (S s) -> after.convert(convert(s));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.springframework.core.convert.converter;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
/**
|
||||
* Tests for {@link Converter}
|
||||
*
|
||||
* @author Josh Cummings
|
||||
*/
|
||||
public class ConverterTests {
|
||||
Converter<Integer, Integer> moduloTwo = number -> number % 2;
|
||||
|
||||
@Test
|
||||
public void andThenWhenGivenANullConverterThenThrowsException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.moduloTwo.andThen(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void andThenWhenGivenConverterThenComposesInOrder() {
|
||||
Converter<Integer, Integer> addOne = number-> number + 1;
|
||||
assertThat(this.moduloTwo.andThen(addOne).convert(13)).isEqualTo(2);
|
||||
assertThat(addOne.andThen(this.moduloTwo).convert(13)).isEqualTo(0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user