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

net.intelie.pipes.Scope Maven / Gradle / Ivy

There is a newer version: 0.25.5
Show newest version
package net.intelie.pipes;

import net.intelie.pipes.util.Preconditions;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Objects;

public class Scope implements Iterable, Serializable {
    private static final long serialVersionUID = 1L;

    private final Scope parent;
    private final Object object;

    public Scope(Object object) {
        this(null, object);
    }

    public Scope(Scope parent, Object object) {
        this.parent = parent;
        this.object = object;
    }

    public Scope parent() {
        return parent;
    }

    public Object object() {
        return object;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Scope)) return false;

        Scope scope = (Scope) o;

        return Objects.equals(this.parent, scope.parent) &&
                Objects.equals(this.object, scope.object);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.parent, this.object);
    }

    @Override
    public String toString() {
        if (this.parent != null)
            return this.parent + "->" + this.object;
        return String.valueOf(this.object);
    }

    public Object get(int depth) {
        if (depth == 0) return object;
        if (parent == null || depth < 0) return null;
        return parent.get(depth - 1);
    }

    @Override
    public Iterator iterator() {
        return new MyIterator();
    }

    private class MyIterator implements Iterator, Serializable {
        private static final long serialVersionUID = 1L;

        private Scope current = Scope.this;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Object next() {
            Preconditions.checkState(hasNext(), "no more elements to iterate");
            Object obj = current.object;
            current = current.parent;
            return obj;
        }
    }
}