Saw something interesting in a modern Scala codebase and extrapolated this out of it:
/** Helpers to make Option syntax more succinct. */
object OptionUtils {
/** Shortcut type symbol for the Option type. */
type ?[A] = Option[A]
/** Enables `foo.?` instead of `Some(foo)` */
implicit class OptionSome[A](val a: A) extends AnyVal {
@inline def `?`: ?[A] = Option(a)
}
implicit class OptionOps[A](val option: ?[A]) extends AnyVal {
/** Enables `foo.!` instead of `foo.get`. Use with caution as usual! */
@inline def `!`: A = option.get
/** Enables `foo ?? bar` instead of `foo.getOrElse(bar)`. Called the
nil-coalescing operator in Swift. */
@inline def `??`(default: => A): A = option.getOrElse(default)
/** Enables `foo ?? bar` instead of `foo.orElse(bar)`. */
@inline def `??`(default: => ?[A]): ?[A] = option.orElse(default)
}
}
Thoughts? Complaints? Note that Swift provides similar syntax ( https://developer.apple.com/documentation/swift/optional#2849660 ), so it’s not terribly innovative.