
This means that Kotlin’s equivalent for flatMap() and map() are similar. With Kotlin’s null system, the value is either present, or null, so there’s nothing to unwrap. To do this, you use flatMap() instead of map(). When mapping an Optional in Java, sometimes you have to unwrap another Optional. For example: present.map(String::length) This happens when you’re mapping to a property or function on the nullable variable.

In some cases, it’s not necessary to call let() at all. Since our example uses a nullable String, be careful not to accidentally use the extension function CharSequence.map(), which will map each character of the String instead of the String itself. The map() method allows you to transform an Optional to an Optional of another value. Optional s4 = Optional.ofNullable("Hello") The Kotlin equivalent is straightforward. The ofNullable() method works the same as of(), except that instead of throwing a NullPointerException, a null value produces an empty. In Kotlin, we have to go out of our way to throw the exception. The of() method creates an Optional if a value is present, or forces an immediate NullPointerException otherwise. The Kotlin equivalent of assigning an empty() is to assign a null.

Static Optional absent = Optional.empty() To explore all of the possibilities, we’ll assume these constants: static Optional present = Optional.of("Hello") Then we’ll wrap up with a few more thoughts about the trade-offs between using Optional and using Kotlin with nullable types. In this guide, we’ll take a look at how Kotlin’s null-safety features can be used to replace Java 8’s Optional class. What should you do? Should you leave them as Optional, or change them to more idiomatic Kotlin?

When Java 8 introduced Streams for operating on collections of data, it also introduced a similar concept, Optional, which has many methods that are similar to Stream, but operates on a single value that might or might not be present.Īs you migrate your projects from Java to Kotlin, you might come across some Optional objects.
