Is there a recommended idiomatic way to adapt a Java Optional to a Kotlin nullable?

90 Views Asked by At

I am writing Kotlin code that uses a Java library which uses Optionals, and I would prefer to use Kotlin's nullable idiom in Kotlin-world.

For example, my library may have a function

Optional<Foo> getFoo(String fooId) {
  ...
}

and in my Kotlin program I want to

foo: Foo? = /* something, something */ getFoo(fooId)

I know that I can do something like

lateinit var foo: Foo?
val fooOpt = getFoo(fooId)
if(fooOpt.isPresent) foo = fooOpt.get()
else foo = null

But, given that Java's Optional serves pretty much the same purpose as a nullable, this seems unnecessarily verbose, even if I collapse it to

val foo: Foo? = getFoo(fooId).orElse(null)
1

There are 1 best solutions below

0
Sweeper On BEST ANSWER

There is a built-in method for this in the Kotlin standard library - getOrNull.

val foo = getFoo(fooId).getOrNull()

Note that if you use orElse(null), you should not call get first.

// this also works, but
// the difference here is that foo here will be a platform type,
// unless you say ": Foo?" explicitly
val foo = getFoo(fooId).orElse(null)