Register now for Android Dev Summit 2019!

Optional

abstract class Optional<T : Any!> : Serializable
kotlin.Any
   ↳ androidx.camera.core.impl.utils.Optional

An immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing (in which case we say that the reference is "absent"); it is never said to "contain null".

A non-null Optional<T> reference can be used as a replacement for a nullable T reference. It allows you to represent "a T that must be present" and a "a T that might be absent" as two distinct types in your program, which can aid clarity.

Some uses of this class include

  • As a method return type, as an alternative to returning null to indicate that no value was available
  • To distinguish between "unknown" (for example, not present in a map) and "known to have no value" (present in the map, with value Optional.absent())
  • To wrap nullable references for storage in a collection that does not support null (though there are several other approaches to this that should be considered first)

A common alternative to using this class is to find or create a suitable null object for the type in question.

This class is not intended as a direct analogue of any existing "option" or "maybe" construct from other programming environments, though it may bear some similarities.

Comparison to java.util.Optional (JDK 8 and higher): A new Optional class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot share a common supertype). All known differences are listed either here or with the relevant methods below.

  • This class is serializable; java.util.Optional is not.
  • java.util.Optional has the additional methods ifPresent, filter, flatMap, and orElseThrow.
  • java.util offers the primitive-specialized versions OptionalInt, OptionalLong and OptionalDouble, the use of which is recommended; Guava does not have these.

Summary

Public methods

open static Optional<T>!

Returns an Optional instance with no contained reference.

abstract Boolean
equals(@Nullable other: Any?)

Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent.

open static Optional<T>!
fromNullable(@Nullable nullableReference: T?)

If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns Optional#absent.

abstract T
get()

Returns the contained instance, which must be present.

abstract Int

Returns a hash code for this instance.

abstract Boolean

Returns true if this holder contains a (non-null) instance.

open static Optional<T>!
of(reference: T)

Returns an Optional instance containing the given non-null reference.

abstract T
or(defaultValue: T)

Returns the contained instance if it is present; defaultValue otherwise.

abstract Optional<T>!
or(secondChoice: Optional<out T>!)

Returns this Optional if it has a value present; secondChoice otherwise.

abstract T
or(supplier: Supplier<out T>!)

Returns the contained instance if it is present; supplier.get() otherwise.

abstract T?

Returns the contained instance if it is present; null otherwise.

abstract String

Returns a string representation for this instance.

Public methods

absent

open static fun <T : Any!> absent(): Optional<T>!

Returns an Optional instance with no contained reference.

Comparison to java.util.Optional: this method is equivalent to Java 8's Optional.empty.

equals

abstract fun equals(@Nullable other: Any?): Boolean

Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent. Note that Optional instances of differing parameterized types can be equal.

Comparison to java.util.Optional: no differences.

fromNullable

open static fun <T : Any!> fromNullable(@Nullable nullableReference: T?): Optional<T>!

If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns Optional#absent.

Comparison to java.util.Optional: this method is equivalent to Java 8's Optional.ofNullable.

get

abstract fun get(): T

Returns the contained instance, which must be present. If the instance might be absent, use or(Object) or orNull instead.

Comparison to java.util.Optional: when the value is absent, this method throws IllegalStateException, whereas the Java 8 counterpart throws .

Exceptions
IllegalStateException if the instance is absent (isPresent returns false); depending on this specific exception type (over the more general ) is discouraged

hashCode

abstract fun hashCode(): Int

Returns a hash code for this instance.

Comparison to java.util.Optional: this class leaves the specific choice of hash code unspecified, unlike the Java 8 equivalent.

isPresent

abstract fun isPresent(): Boolean

Returns true if this holder contains a (non-null) instance.

Comparison to java.util.Optional: no differences.

of

open static fun <T : Any!> of(reference: T): Optional<T>!

Returns an Optional instance containing the given non-null reference. To have null treated as absent, use fromNullable instead.

Comparison to java.util.Optional: no differences.

Exceptions
NullPointerException if reference is null

or

abstract fun or(defaultValue: T): T

Returns the contained instance if it is present; defaultValue otherwise. If no default value should be required because the instance is known to be present, use get() instead. For a default value of null, use orNull.

Note about generics: The signature public T or(T defaultValue) is overly restrictive. However, the ideal signature, public <S super T> S or(S), is not legal Java. As a result, some sensible operations involving subtypes are compile errors:

<code>Optional&lt;Integer&gt; optionalInt = getSomeOptionalInt();
      Number value = optionalInt.or(0.5); // error
     
      FluentIterable&lt;? extends Number&gt; numbers = getSomeNumbers();
      Optional&lt;? extends Number&gt; first = numbers.first();
      Number value = first.or(0.5); // error
      </code>

As a workaround, it is always safe to cast an Optional<? extends T> to Optional<T>. Casting either of the above example Optional instances to Optional<Number> (where Number is the desired output type) solves the problem:

<code>Optional&lt;Number&gt; optionalInt = (Optional) getSomeOptionalInt();
      Number value = optionalInt.or(0.5); // fine
     
      FluentIterable&lt;? extends Number&gt; numbers = getSomeNumbers();
      Optional&lt;Number&gt; first = (Optional) numbers.first();
      Number value = first.or(0.5); // fine
      </code>

Comparison to java.util.Optional: this method is similar to Java 8's Optional.orElse, but will not accept null as a defaultValue (orNull must be used instead). As a result, the value returned by this method is guaranteed non-null, which is not the case for the java.util equivalent.

or

abstract fun or(secondChoice: Optional<out T>!): Optional<T>!

Returns this Optional if it has a value present; secondChoice otherwise.

Comparison to java.util.Optional: this method has no equivalent in Java 8's Optional class; write thisOptional.isPresent() ? thisOptional : secondChoice instead.

or

abstract fun or(supplier: Supplier<out T>!): T

Returns the contained instance if it is present; supplier.get() otherwise.

Comparison to java.util.Optional: this method is similar to Java 8's Optional.orElseGet, except when supplier returns null. In this case this method throws an exception, whereas the Java 8 method returns the null to the caller.

Exceptions
NullPointerException if this optional's value is absent and the supplier returns null

orNull

@Nullable abstract fun orNull(): T?

Returns the contained instance if it is present; null otherwise. If the instance is known to be present, use get() instead.

Comparison to java.util.Optional: this method is equivalent to Java 8's Optional.orElse(null).

toString

abstract fun toString(): String

Returns a string representation for this instance.

Comparison to java.util.Optional: this class leaves the specific string representation unspecified, unlike the Java 8 equivalent.