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

com.yahoo.lang.SettableOptional Maven / Gradle / Ivy

Go to download

Library for use in Java components of Vespa. Shared code which do not fit anywhere else.

There is a newer version: 8.409.18
Show newest version
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.lang;

import java.util.NoSuchElementException;
import java.util.Optional;

/**
 * An optional which contains a settable value
 *
 * @author bratseth
 */
public final class SettableOptional {

    private T value = null;

    /** Creates a new empty settable optional */
    public SettableOptional() {}

    /** Creates a new settable optional with the given value */
    public SettableOptional(T value) { this.value = value; }

    /** Creates a new settable optional with the given value, or an empty */
    public SettableOptional(Optional value) {
        this.value = value.orElse(null);
    }

    public boolean isPresent() {
        return value != null;
    }

    public T get() {
        if (value == null)
            throw new NoSuchElementException("No value present");
        return value;
    }

    public void set(T value) {
        this.value = value;
    }

    public void set(Optional value) {
        this.value = value.orElse(null);
    }
    
    public Optional asOptional() {
        if (value == null) return Optional.empty();
        return Optional.of(value);
    }

}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy