001/************************************************************************
002 * Licensed under Public Domain (CC0)                                    *
003 *                                                                       *
004 * To the extent possible under law, the person who associated CC0 with  *
005 * this code has waived all copyright and related or neighboring         *
006 * rights to this code.                                                  *
007 *                                                                       *
008 * You should have received a copy of the CC0 legalcode along with this  *
009 * work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.*
010 ************************************************************************/
011
012package org.reactivestreams.tck.flow.support;
013
014import java.util.NoSuchElementException;
015
016// simplest possible version of Scala's Option type
017public abstract class Optional<T> {
018
019  private static final Optional<Object> NONE = new Optional<Object>() {
020    @Override
021    public Object get() {
022      throw new NoSuchElementException(".get call on None!");
023    }
024
025    @Override
026    public boolean isEmpty() {
027      return true;
028    }
029  };
030
031  private Optional() {
032  }
033
034  @SuppressWarnings("unchecked")
035  public static <T> Optional<T> empty() {
036    return (Optional<T>) NONE;
037  }
038
039  @SuppressWarnings("unchecked")
040  public static <T> Optional<T> of(T it) {
041    if (it == null) return (Optional<T>) Optional.NONE;
042    else return new Some(it);
043  }
044
045  public abstract T get();
046
047  public abstract boolean isEmpty();
048
049  public boolean isDefined() {
050    return !isEmpty();
051  }
052
053  public static class Some<T> extends Optional<T> {
054    private final T value;
055
056    Some(T value) {
057      this.value = value;
058    }
059
060    @Override
061    public T get() {
062      return value;
063    }
064
065    @Override
066    public boolean isEmpty() {
067      return false;
068    }
069
070    @Override
071    public String toString() {
072      return String.format("Some(%s)", value);
073    }
074  }
075
076  @Override
077  public String toString() {
078    return "None";
079  }
080}