How to map java.util.Optional<Something> to Something? in Kotlin

Extend the java API with a method to unwrap Optional:

fun <T> Optional<T>.unwrap(): T? = orElse(null)

Then use it like you wanted:

val msg: Something? = optional.unwrap()  // the type is enforced

See https://kotlinlang.org/docs/reference/extensions.html for details.


If you use com.google.common.base.Optional (Guava library) then orNull() is better.

For example,

// Java
public class JavaClass
  public Optional<String> getOptionalString() {
    return Optional.absent();
  }
}

// Kotlin
val optionalString = JavaClass().getOptionalString().orNull()

The definition of orNull()

/**
 * Returns the contained instance if it is present; {@code null} otherwise. If the instance is
 * known to be present, use {@link #get()} instead.
 *
 * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
 * {@code Optional.orElse(null)}.
 */
@Nullable
public abstract T orNull();