How to match java.util.Optional <Something> with something? in Kotlin

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

How to do this in Kotlin, idiomatically?

calling .orElse(null) on Optional really gives me Something? but he doesn’t look very good. Kotlin doesn't complain if I write val msg: Something = optional.orElse(null). ( msg declared as Something , not Something? - I lost compilation type checking).

I am using Kotlin 1.0.3

+8
java-8 kotlin optional
source share
2 answers

Extend the java API with the Optional deployment method:

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

Then use it as you like:

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

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

+13
source share

orNull() better.

For example,

 // Java public class JavaClass public Optional<String> getOptionalString() { return Optional.absent(); } } // Kotlin val optionalString = JavaClass().getOptionalString().orNull() 

orNull() definition

 /** * 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(); 
+1
source share

All Articles