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.
0 Comments
Leave a Reply. |