Skip to content

Instantly share code, notes, and snippets.

@bastman
Created January 31, 2018 10:39
Show Gist options
  • Save bastman/87faa0e410d08f1650c319a331418665 to your computer and use it in GitHub Desktop.
Save bastman/87faa0e410d08f1650c319a331418665 to your computer and use it in GitHub Desktop.
Kotlin extension function to convert Java8 Optional<T> to Kotlin nullable T?
fun <T : Any> Optional<T>.toNullable(): T? {
return if (this.isPresent) {
this.get()
} else {
null
}
}
@Hydragyrum
Copy link

fun <T : Any> Optional<T>.toNullable(): T? = this.orElse(null);

is more succint IMO

@jayhilden
Copy link

jayhilden commented Nov 21, 2019

nice! And the reverse.

fun <T : Any> T?.toOptional(): Optional<T> = Optional.ofNullable(this)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment