Last active
November 14, 2019 20:46
-
-
Save julienroubieu/fbb7e1467ab44203a09f to your computer and use it in GitHub Desktop.
Implicit conversions between Scala Option and Java 8 Optional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Optional | |
| /** | |
| * Implicit conversions between Scala Option and Java 8 Optional. | |
| */ | |
| object JavaOptionals { | |
| /** | |
| * Transform a Scala Option[T] to a Java Optional[T] | |
| */ | |
| implicit def toRichOption[T](opt: Option[T]): RichOption[T] = new RichOption[T](opt) | |
| /** | |
| * Transform a Java Optional[T] to a Scala Option[T] | |
| */ | |
| implicit def toRichOptional[T](optional: Optional[T]): RichOptional[T] = new RichOptional[T](optional) | |
| } | |
| class RichOption[T] (opt: Option[T]) { | |
| def toOptional: Optional[T] = Optional.ofNullable(opt.getOrElse(null).asInstanceOf[T]) | |
| } | |
| class RichOptional[T] (opt: Optional[T]) { | |
| 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