I'm taking my first steps with kotlin.
I am migrating some my existing java code to kotlin.
I have the folllowing line:
storyDate.ifPresent(article::setPublishDate);
Where storyDate is an Optional and article has a method setPublishDate(Date) method.
How would I migrate this line to kotlin?
The auto migrator at https://try.kotlinlang.org is
storyDate.ifPresent(Consumer<Date>({ article.setPublishDate() }))
But this line doesn't compile with the kotlin compiler.
I strongly prefer using extension functions and extension fields, so I've written smth like
val <T> Optional<T>.value: T?
get() = orElse(null)
And then you can use it anywhere (after import) like
myOptional.value?.let {
// handle here
}
It’s rather uncommon to use Optional
in Kotlin. If you can make storyDate
work as an ordinary unwrapped type, such constructs can often be expressed with a simple let
call:
storyDate?.let {
article.setPublishDate(it)
//probably property access works as well:
article.publishDate = it
}
How it works: The safe call ?.
will invoke let
only if storyDate
is not null
, otherwise the whole expression evaluates to, again, null
. When the variable is not null
, let
is called with a simple lambda where storyDate
is accessible by it
(or you can rename it to whatever you like).
Side note:
If storyDate
really must be Optional
, you can still use the depicted construct by unwrapping it like this:
storyDate.orElse(null)?.let {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With