Class Optional<T>

Object
org.apache.spark.api.java.Optional<T>
Type Parameters:
T - type of value held inside
All Implemented Interfaces:
Serializable

public final class Optional<T> extends Object implements Serializable

Like java.util.Optional in Java 8, scala.Option in Scala, and com.google.common.base.Optional in Google Guava, this class represents a value of a given type that may or may not exist. It is used in methods that wish to optionally return a value, in preference to returning null.

In fact, the class here is a reimplementation of the essential API of both java.util.Optional and com.google.common.base.Optional. From java.util.Optional, it implements:

From com.google.common.base.Optional it implements:

java.util.Optional itself was not used because at the time, the project did not require Java 8. Using com.google.common.base.Optional has in the past caused serious library version conflicts with Guava that can't be resolved by shading. Hence this work-alike clone.

See Also:
  • Method Details

    • empty

      public static <T> Optional<T> empty()
      Returns:
      an empty Optional
    • of

      public static <T> Optional<T> of(T value)
      Parameters:
      value - non-null value to wrap
      Returns:
      Optional wrapping this value
      Throws:
      NullPointerException - if value is null
    • ofNullable

      public static <T> Optional<T> ofNullable(T value)
      Parameters:
      value - value to wrap, which may be null
      Returns:
      Optional wrapping this value, which may be empty
    • get

      public T get()
      Returns:
      the value wrapped by this Optional
      Throws:
      NullPointerException - if this is empty (contains no value)
    • orElse

      public T orElse(T other)
      Parameters:
      other - value to return if this is empty
      Returns:
      this Optional's value if present, or else the given value
    • isPresent

      public boolean isPresent()
      Returns:
      true iff this Optional contains a value (non-empty)
    • absent

      public static <T> Optional<T> absent()
      Returns:
      an empty Optional
    • fromNullable

      public static <T> Optional<T> fromNullable(T value)
      Parameters:
      value - value to wrap, which may be null
      Returns:
      Optional wrapping this value, which may be empty
    • or

      public T or(T other)
      Parameters:
      other - value to return if this is empty
      Returns:
      this Optional's value if present, or else the given value
    • orNull

      public T orNull()
      Returns:
      this Optional's value if present, or else null
    • equals

      public boolean equals(Object obj)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • toString

      public String toString()
      Overrides:
      toString in class Object