Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrate Java Option call to kotlin

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.

like image 367
Michael Wiles Avatar asked Oct 15 '25 23:10

Michael Wiles


2 Answers

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
}
like image 92
asm0dey Avatar answered Oct 18 '25 17:10

asm0dey


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 {}
like image 25
s1m0nw1 Avatar answered Oct 18 '25 18:10

s1m0nw1