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)
There is a built-in method for this in the Kotlin standard library -
getOrNull.Note that if you use
orElse(null), you should not callgetfirst.