Skip to content

Instantly share code, notes, and snippets.

@DavidDudson
Created November 7, 2017 22:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidDudson/dee0d6ac075919a57090b45a450ec70b to your computer and use it in GitHub Desktop.
Save DavidDudson/dee0d6ac075919a57090b45a450ec70b to your computer and use it in GitHub Desktop.
Allocationless Option type that converts to/from scala.Option and java.Optional
/**
* An Option class, without a few Ion's
*
* Never allocates, uses null instead.
*
* No primitives allowed.
*
* Flatmap is allowed, but nesting is not (no flatten)
*/
object Opt {
type Opt[A <: AnyRef]
@inline
def apply[A <: AnyRef](a: A): Opt[A] =
a.asInstanceOf[Opt[A]]
@inline
def fromOption[A <: AnyRef](oa: Option[A])(implicit ev: Null <:< A): Opt[A] =
Opt(oa.orNull)
@inline
def empty[A <: AnyRef]: Opt[A] =
null.asInstanceOf[Opt[A]]
// Slightly duplicated due to not storing methods outside of OptImplicits
def unapply[A <: AnyRef](arg: Opt[A]): Option[A] =
Option(arg.asInstanceOf[A])
}
/**
* No allocation methods to treat Opt as if it was a class
*/
object OptOps {
import psenterprise.lang.gproms.Opt._
implicit class OptImplicits[A <: AnyRef](val opt: Opt[A]) extends AnyVal {
def flatMap[B <: AnyRef](f: A => Opt[B]): Opt[B] =
if (opt.isEmpty) empty[B] else f(raw)
def map[B <: AnyRef](f: A => B): Opt[B] =
if (opt.isEmpty) empty[B] else Opt(f(raw))
def forEach(f: A => Unit): Unit =
if (opt.nonEmpty) f(raw)
// a strict version of getOrElse
def getOrThat(orElse: => A): A =
if (opt.isEmpty) orElse else raw
def filter(f: A => Boolean): Opt[A] =
if (opt.isEmpty || !f(raw)) empty[A] else opt
def filterNot(f: A => Boolean): Opt[A] =
if (opt.isEmpty || f(raw)) empty[A] else opt
@inline
def collect[B <: AnyRef](pf: PartialFunction[A, B]): Opt[B] =
if (pf.isDefinedAt(raw)) Opt(pf(raw)) else empty[B]
// == is nullsafe
@inline
def contains(a: A): Boolean =
a == raw
def exists(f: A => Boolean): Boolean =
!opt.isEmpty && f(raw)
@inline
def isEmpty =
opt == null
@inline
def nonEmpty =
opt != null
@inline
def toOption: Option[A] =
Option(raw)
@inline
def orNull: A =
raw
@inline
def toOptional: Optional[A] =
Optional.ofNullable(raw)
/** Unwrapped raw value of opt */
@inline
private def raw: A =
opt.asInstanceOf[A]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment