Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Applicative Functor in Guava
import com.google.common.base.Function;
import com.google.common.base.Optional;
import org.junit.Test;
import javax.annotation.Nullable;
import static org.fest.assertions.Assertions.assertThat;
public class OptionalTest {
@Test
public void should_() {
Optional<String> string = getSomething(true);
Optional<Optional<String>> result = Optional.of(string).transform(ID_FUNCTION).transform(FAIL_FUNCTION).transform(addString(" world!"));
assertThat(flatten(result).or("Fail")).isEqualTo("Fail");
}
private static <T> Optional<T> flatten(Optional<Optional<T>> optional) {
if (optional.isPresent()) {
return optional.get();
}
return Optional.absent();
}
private Optional<String> getSomething(boolean b) {
return b ? Optional.of("Hello") : Optional.<String>absent();
}
public static final Function<Optional<String>,Optional<String>> ID_FUNCTION = new Function<Optional<String>, Optional<String>>() {
@Override
public Optional<String> apply(@Nullable Optional<String> input) {
return input;
}
};
public static final Function<Optional<String>,Optional<String>> FAIL_FUNCTION = new Function<Optional<String>, Optional<String>>() {
@Override
public Optional<String> apply(@Nullable Optional<String> input) {
return Optional.absent();
}
};
private Function<Optional<String>, Optional<String>> addString(final String value) {
return new Function<Optional<String>, Optional<String>>() {
@Override
public Optional<String> apply(@Nullable Optional<String> input) {
if (!input.isPresent()) {
return input;
} else {
return Optional.of(input.get() + value);
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.