All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.bluecatcode.common.base.Right Maven / Gradle / Ivy

The newest version!
package com.bluecatcode.common.base;

import com.bluecatcode.common.contract.errors.ContractViolation;
import com.google.common.base.Function;
import com.google.common.base.Objects;

import javax.annotation.Nullable;

import static com.bluecatcode.common.contract.Preconditions.require;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;

/**
 * Implementation of an {@link Either} containing a right reference.
 */
final class Right extends Either {

    private static final long serialVersionUID = 0L;

    private final R right;

    Right(R right) {
        this.right = checkNotNull(right, "Expected non-null right");
    }

    @Override
    public boolean isLeft() {
        return false;
    }

    @Override
    public boolean isRight() {
        return true;
    }

    @Override
    public L left() {
        throw new ContractViolation("Left value is absent");
    }

    @Override
    public R right() {
        return this.right;
    }

    @Override
    public Either or(Either secondChoice) {
        require(secondChoice != null, "Expected non-null secondChoice");
        return this;
    }

    @Override
    public  R orThrow(Function leftFunction) throws E {
        require(leftFunction != null, "Expected non-null leftFunction");
        return right;
    }

    @Override
    public  V either(Function leftFunction, Function rightFunction) {
        require(rightFunction != null, "Expected non-null rightFunction");
        return rightFunction.apply(right());
    }

    @Override
    public  Either transform(Function leftFunction, Function rightFunction) {
        require(rightFunction != null, "Expected non-null rightFunction");
        //noinspection ConstantConditions
        return rightOf(rightFunction.apply(right()));
    }

    @Override
    public Either swap() {
        return leftOf(right());
    }

    @Override
    public boolean equals(@Nullable Object other) {
        if (this == other) return true;
        if (other == null || getClass() != other.getClass()) return false;
        Right right1 = (Right) other;
        return Objects.equal(right, right1.right);
    }

    @Override
    public int hashCode() {
        return 0xc4dcd0b4 + right.hashCode();
    }

    @Override
    public String toString() {
        return format("Right.of(%s)", right);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy