Scala Maybe

I wrote a Maybe that I can use in Scala.

Scala Maybe

… because I wanted a lazy variant of Option[+T] for those cases where Gradle needs me to produce something, but, I know darn well that the rest of the project model hasn’t been setup.

package peterlavalle

/**
    * like Option[+A] but lazy
    */
trait Maybe[+T] {
    def bind[V](map: T => V): Maybe[V]

    def some: Option[T]
}

object Maybe {

    case object Nope extends Maybe[Nothing] {
        override def bind[V](map: Nothing => V): Maybe[V] = Nope

        override val some: Option[Nothing] = None
    }

    private class Just[T](read: => T) extends Maybe[T] {
        lazy val some: Option[T] = Some(read)

        override def bind[V](map: T => V): Maybe[V] =
            Maybe {
                map {
                    some.get
                }
            }
    }

    def apply[T](readit: => T): Maybe[T] = new Just[T](readit)

    def unapply[T](arg: Maybe[T]): Option[T] = arg.some
}
Peter LaValle avatar
About Peter LaValle
honks at geese. speaks the byzantine languages that make the magic boxes do the things. Someday maybe I'll retire and be a graphics programmer or demoscene coder.
comments powered by Disqus