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

com.thejohnfreeman.lazy.Thunk5 Maven / Gradle / Ivy

Go to download

A library for type-safe, tractable lazy evaluation and late binding in Java.

The newest version!
package com.thejohnfreeman.lazy;

import com.google.common.collect.ImmutableList;

import com.thejohnfreeman.function.Function5;

/**
 * A lazy value computed from five 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
 * @param  the type of the fourth dependency
 * @param  the type of the fifth dependency
 */
public final class Thunk5
    extends AbstractThunk
{
    private Lazy _depA;
    private Lazy _depB;
    private Lazy _depC;
    private Lazy _depD;
    private Lazy _depE;
    private Function5 _func;

    private Thunk5(
        final Lazy a, final Lazy b, final Lazy c, final Lazy d, final Lazy e,
        final Function5 func)
    {
        _depA = a;
        _depB = b;
        _depC = c;
        _depD = d;
        _depE = e;
        _func = func;
    }

    public static  Thunk5 of(
        final Lazy a, final Lazy b, final Lazy c, final Lazy d, final Lazy e,
        final Function5 func)
    {
        return new Thunk5<>(a, b, c, d, e, func);
    }

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

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

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

    @Override
    public String toStringUnforced(final String name) {
        return "(_5_) -> " + name;
    }
}