39 lines
1002 B
Plaintext
39 lines
1002 B
Plaintext
``++Optional++`` value can hold either a value or not. The value held in the ``++Optional++`` can be accessed using the ``++get()++`` method, but it will throw a
|
|
``++NoSuchElementException++`` if there is no value present. To avoid the exception, calling the ``++isPresent()++`` or ``++! isEmpty()++`` method should always be done before any call to ``++get()++``.
|
|
|
|
Alternatively, note that other methods such as ``++orElse(...)++``, ``++orElseGet(...)++`` or ``++orElseThrow(...)++`` can be used to specify what to do with an empty ``++Optional++``.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
Optional<String> value = this.getOptionalValue();
|
|
|
|
// ...
|
|
|
|
String stringValue = value.get(); // Noncompliant
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
Optional<String> value = this.getOptionalValue();
|
|
|
|
// ...
|
|
|
|
if (value.isPresent()) {
|
|
String stringValue = value.get();
|
|
}
|
|
----
|
|
|
|
or
|
|
|
|
----
|
|
Optional<String> value = this.getOptionalValue();
|
|
|
|
// ...
|
|
|
|
String stringValue = value.orElse("default");
|
|
----
|
|
|
|
include::../see.adoc[]
|