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

org.daisy.pipeline.braille.common.LazyValue Maven / Gradle / Ivy

There is a newer version: 5.0.2
Show newest version
package org.daisy.pipeline.braille.common;

import java.util.Iterator;
import java.util.NoSuchElementException;

import org.daisy.pipeline.braille.common.util.Function0;

public abstract class LazyValue implements Function0, Iterable {
	
	public Iterator iterator() {
		return new Iterator() {
			boolean hasNext = true;
			public boolean hasNext() {
				return hasNext;
			}
			public V next() {
				if (!hasNext())
					throw new NoSuchElementException();
				hasNext = false;
				return apply();
			}
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}
	
	public static  LazyValue from(final Function0 value) {
		return new LazyValue() {
			public V apply() {
				return value.apply();
			}
		};
	}
	
	public static abstract class ImmutableLazyValue extends LazyValue {
		
		private V value = null;
		protected boolean computed = false;
		
		public final V apply() {
			if (!computed) {
				value = _apply();
				computed = true; }
			return value;
		}
		
		protected abstract V _apply();
		
		public static  LazyValue from(final Function0 value) {
			return new ImmutableLazyValue() {
				public V _apply() {
					return value.apply();
				}
			};
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy