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

com.github.davidmoten.util.Optional Maven / Gradle / Ivy

package com.github.davidmoten.util;

import rx.Observable;

public class Optional {

    private final T value;
    private final boolean present;

    private Optional(T value, boolean present) {
        this.value = value;
        this.present = present;
    }

    public boolean isPresent() {
        return present;
    }

    public T get() {
        if (present)
            return value;
        else
            throw new NotPresentException();
    }

    public T or(T alternative) {
        if (present)
            return value;
        else
            return alternative;
    }

    public Observable toObservable() {
        if (present)
            return Observable.just(value);
        else
            return Observable.empty();
    }

    public static  Optional fromNullable(T t) {
        if (t == null)
            return Optional.absent();
        else
            return Optional.of(t);
    }

    public static  Optional of(T t) {
        return new Optional(t, true);
    }

    public static  Optional absent() {
        return new Optional(null, false);
    }

    public static class NotPresentException extends RuntimeException {

        private static final long serialVersionUID = -4444814681271790328L;

    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy