Java tutorial
/* * #%L * Osbolab Commons * %% * Copyright (C) 2014 Osbolab LLC * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package com.osbolab.commons; import com.google.common.base.Function; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.atlassian.fugue.Either; import com.atlassian.fugue.Option; import com.osbolab.commons.function.Effect; /** * @author matt@osbolab.com (Matt Barnard) */ public class MoreEithers { public static <L, T> boolean isLeftOrEmpty(Either<L, Option<T>> from) { return from.isLeft() || from.right().get().isEmpty(); } public static <L, T> boolean fold(Either<L, Option<T>> from, Effect<L> l, Effect<T> r) { if (from.isLeft()) { l.apply(from.left().get()); return true; } else { if (!from.right().get().isEmpty()) { r.apply(from.right().get().get()); return true; } } return false; } public static <L, T, R> Option<R> fold(Either<L, Option<T>> from, Function<L, R> l, Function<T, R> r) { if (from.isLeft()) { return Option.some(l.apply(from.left().get())); } else { if (!from.right().get().isEmpty()) { return Option.some(r.apply(from.right().get().get())); } } return Option.none(); } public static <L, T> Either<L, Option<T>> someRight(T of) { return Either.right(Option.some(of)); } public static <L, T> ListenableFuture<Either<L, Option<T>>> someFutureRight(T of) { return Futures.immediateFuture(MoreEithers.<L, T>someRight(of)); } public static <L, R> ListenableFuture<Either<L, R>> futureRight(R of) { return Futures.immediateFuture(Either.<L, R>right(of)); } }