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

com.jfreeman.lazy.TriThunk Maven / Gradle / Ivy

package com.jfreeman.lazy;

import java.util.List;

import com.google.common.collect.ImmutableList;

import com.jfreeman.function.TriFunction;

/**
 * A lazy value with three dependencies.
 *
 * @param  the type of the value
 * @param  the type of the first dependency
 * @param  the type of the second dependency
 * @param  the type of the third dependency
 * @author jfreeman
 */
class TriThunk
    implements Lazy
{
    private Lazy _depA;
    private Lazy _depB;
    private Lazy _depC;
    /** @see Thunk#_func */
    private TriFunction _func;
    /** @see Thunk#_value */
    private T _value = null;

    private TriThunk(
        Lazy a, Lazy b, Lazy c, TriFunction func)
    {
        _depA = a;
        _depB = b;
        _depC = c;
        _func = func;
    }

    public static  TriThunk of(
        Lazy a, Lazy b, Lazy c, TriFunction func)
    {
        return new TriThunk<>(a, b, c, func);
    }

    @Override
    public boolean isForced() {
        return _func == null;
    }

    @Override
    public List> getDependencies()
        throws IllegalStateException
    {
        if (isForced()) {
            throw new IllegalStateException("already forced");
        }
        return ImmutableList.of(_depA, _depB, _depC);
    }

    @Override
    public T force()
        throws IllegalStateException
    {
        if (isForced()) {
            throw new IllegalStateException("already forced");
        }
        final A a = _depA.getValue();
        final B b = _depB.getValue();
        final C c = _depC.getValue();
        _value = _func.apply(a, b, c);
        _func = null;
        _depA = null;
        _depB = null;
        _depC = null;
        return _value;
    }

    @Override
    public T getValue()
        throws IllegalStateException
    {
        if (!isForced()) {
            throw new IllegalStateException("not yet forced");
        }
        return _value;
    }
}