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
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.
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.
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.
In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .
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();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With