001/***************************************************
002 * Licensed under MIT No Attribution (SPDX: MIT-0) *
003 ***************************************************/
004
005package org.reactivestreams.tck.flow.support;
006
007import java.util.NoSuchElementException;
008
009// simplest possible version of Scala's Option type
010public abstract class Optional<T> {
011
012  private static final Optional<Object> NONE = new Optional<Object>() {
013    @Override
014    public Object get() {
015      throw new NoSuchElementException(".get call on None!");
016    }
017
018    @Override
019    public boolean isEmpty() {
020      return true;
021    }
022  };
023
024  private Optional() {
025  }
026
027  @SuppressWarnings("unchecked")
028  public static <T> Optional<T> empty() {
029    return (Optional<T>) NONE;
030  }
031
032  @SuppressWarnings("unchecked")
033  public static <T> Optional<T> of(T it) {
034    if (it == null) return (Optional<T>) Optional.NONE;
035    else return new Some(it);
036  }
037
038  public abstract T get();
039
040  public abstract boolean isEmpty();
041
042  public boolean isDefined() {
043    return !isEmpty();
044  }
045
046  public static class Some<T> extends Optional<T> {
047    private final T value;
048
049    Some(T value) {
050      this.value = value;
051    }
052
053    @Override
054    public T get() {
055      return value;
056    }
057
058    @Override
059    public boolean isEmpty() {
060      return false;
061    }
062
063    @Override
064    public String toString() {
065      return String.format("Some(%s)", value);
066    }
067  }
068
069  @Override
070  public String toString() {
071    return "None";
072  }
073}