blob: 9de1d9914f13932e0716e3faf2c7702bcca6ec21 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
// 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<T> {
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<T> 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<T> value) {
this.value = value.orElse(null);
}
public Optional<T> asOptional() {
if (value == null) return Optional.empty();
return Optional.of(value);
}
}
|