Skip to content

Instantly share code, notes, and snippets.

@julienroubieu
Last active November 14, 2019 20:46
Show Gist options
  • Save julienroubieu/fbb7e1467ab44203a09f to your computer and use it in GitHub Desktop.
Save julienroubieu/fbb7e1467ab44203a09f to your computer and use it in GitHub Desktop.
Implicit conversions between Scala Option and Java 8 Optional
import java.util.Optional
/**
* Conversions between Scala Option and Java 8 Optional.
*/
object JavaOptionals {
implicit def toRichOption[T](opt: Option[T]): RichOption[T] = new RichOption[T](opt)
implicit def toRichOptional[T](optional: Optional[T]): RichOptional[T] = new RichOptional[T](optional)
}
class RichOption[T] (opt: Option[T]) {
/**
* Transform this Option to an equivalent Java Optional
*/
def toOptional: Optional[T] = Optional.ofNullable(opt.getOrElse(null).asInstanceOf[T])
}
class RichOptional[T] (opt: Optional[T]) {
/**
* Transform this Optional to an equivalent Scala Option
*/
def toOption: Option[T] = if (opt.isPresent) Some(opt.get()) else None
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment