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

com.danielsomerfield.util.Maybe.groovy Maven / Gradle / Ivy

There is a newer version: 0.6.2-100
Show newest version
package com.danielsomerfield.util

abstract class Maybe {

  private static final Maybe NOTHING = new Nothing();

  public abstract boolean exists()
  public abstract T getValue()
  public abstract  Maybe map(Closure mapper)

  public static  Maybe some(T value) {
    return value == null ? NOTHING : new Some(value)
  }

  public static  Maybe nothing() {
    NOTHING
  }

  private static class Some extends Maybe {
    private T value;

    public Some(final T value) {
      this.value = value
    }

    public boolean exists() {
      true
    }

    public T getValue(){
      value
    }

    @Override
    def  Maybe map(final Closure mapper) {
      some(mapper(value))
    }

    boolean equals(final o) {
      if (this.is(o)) return true
      if (!(o instanceof Some)) return false

      final Some some = (Some) o

      if (value != some.value) return false

      return true
    }

    int hashCode() {
      return value.hashCode()
    }


    @Override
    public String toString() {
      "Some{" +
          "value=" + value +
          '}';
    }
  }

  private static class Nothing extends Maybe {

    @Override
    boolean exists() {
      return false // TODO
    }

    @Override
    Object getValue() {
      throw new IllegalStateException("Cannot get value of Nothing")
    }

    @Override
    Maybe map(final Closure mapper) {
      this
    }

    public String toString(){"Nothing"}

  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy