Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin equivalent for Optional::map in Java8

Do you know if there is a shortcut for:

if (x == null) null else f(x)

For Java Optional you can just do:

x.map(SomeClass::f)
like image 817
Konrad Avatar asked Jan 26 '18 17:01

Konrad


People also ask

How do I use Optional in Java 8?

Optional is a container object which may or may not contain a non-null value. You must import java. util package to use this class. If a value is present, isPresent() will return true and get() will return the value.

Should we use Optional in Kotlin?

Depending on whom you ask, using Optional as the type of a field or return type is bad practice in Java. Fortunately, in Kotlin there is no arguing about it. Using nullable types in properties or as the return type of functions is considered perfectly valid and idiomatic in Kotlin.

What is .MAP in Kotlin?

Kotlin map is a collection that contains pairs of objects. Map holds the data in the form of pairs which consists of a key and a value. Map keys are unique and the map holds only one value for each key. Kotlin distinguishes between immutable and mutable maps.

What is Optional ofNullable?

What is the ofNullable() method of the Optional class? The ofNullable() method is used to get an instance of the Optional class with a specified value. If the value is null , then an empty Optional object is returned.


1 Answers

Kotlin utilizes its own approach to the idea of Option, but there're map, filter, orElse equivalents:

val x: Int? = 7                 // ofNullable()

val result = x
  ?.let(SomeClass.Companion::f) // map()
  ?.takeIf { it != 0 }          // filter()
  ?: 42                         // orElseGet()

I ended up writing a full comparison here:

like image 112
Grzegorz Piwowarek Avatar answered Oct 27 '22 00:10

Grzegorz Piwowarek