Skip to content

Commit e6698a1

Browse files
authored
add Maybe::optionalValue
Add a method to retrieve the value stored in a Maybe as a Java Optional.
1 parent ba86252 commit e6698a1

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/java/org/tensorics/core/util/Maybe.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,21 @@ public T value() {
116116
return value;
117117
}
118118

119+
/**
120+
* Retrieve the value stored in this {@link Maybe} as an {@link Optional}. If an exception is stored in this Maybe,
121+
* the returned optional will be empty. For a "successful" {@link Maybe}<Void>, it will contain null.
122+
*
123+
* @return the value
124+
* @throws RuntimeException if this Maybe objects contains an exception
125+
*/
126+
public Optional<T> optionalValue() {
127+
if (exception != null) {
128+
return Optional.empty();
129+
} else {
130+
return Optional.of(value);
131+
}
132+
}
133+
119134
/**
120135
* Throw the contained exception, wrapped in a {@link RuntimeException}, if any. If called on a "successful" Maybe,
121136
* this method does nothing.
@@ -308,4 +323,4 @@ public String toString() {
308323
}
309324
}
310325

311-
}
326+
}

0 commit comments

Comments
 (0)