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 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 | |
/** | |
* 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