Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a method that returns java.util.Optional<Something>. I want to use that method from Kotlin, and I want my result to be Something?, not Optional<Something>

How to do that in Kotlin, in idiomatic way?

calling .orElse(null) on Optional gives me Something? indeed, but it does not look good. Kotlin does not complain if I write val msg: Something = optional.orElse(null). (msg is declared as Something, not Something?- I loose compile-type check).

I use Kotlin 1.0.3

like image 883
Bartosz Bilicki Avatar asked Aug 04 '16 12:08

Bartosz Bilicki


People also ask

How does Kotlin handle Optional?

When mapping an Optional in Java, sometimes you have to unwrap another Optional . To do this, you use flatMap() instead of map() . With Kotlin's null system, the value is either present, or null , so there's nothing to unwrap. This means that Kotlin's equivalent for flatMap() and map() are similar.

How do I fetch an object from Optional?

Once you have created an Optional object, you can use the isPresent() method to check if it contains a non-null value. If it does, you can use the get() method to retrieve the value. Developers can also use the getOrElse() method, which will return the value if it is present, or a default value if it is not.

How do I add items to Kotlin map?

Add and update entries To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements are defined by the order of their keys.

How do I convert Optional in Java?

In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .


3 Answers

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.

like image 100
voddan Avatar answered Oct 17 '22 12:10

voddan


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();
like image 26
Jake Lin Avatar answered Oct 17 '22 14:10

Jake Lin


A nullable type in Kotlin can have value or null so you can convert and Optional to nullable Type as follows:

val str: SomeType? = Optional.of(SomeType_Value).map { it }.orElse(null)

For example for SomeType of String we have

val str: String? = Optional.of("someValue").map { it }.orElse(null)
like image 1
Mr.Q Avatar answered Oct 17 '22 14:10

Mr.Q