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.
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 {}