Skip to content

Introduce Converter.andThen(...) #23379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
Expand All @@ -26,6 +27,7 @@
* <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
Expand All @@ -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));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.springframework.core.convert.converter;

import org.junit.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);
}
}