Skip to content

Instantly share code, notes, and snippets.

@gcnyin
Created December 9, 2021 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcnyin/f0eb40816e696769ea8e93d7b69aa58a to your computer and use it in GitHub Desktop.
Save gcnyin/f0eb40816e696769ea8e93d7b69aa58a to your computer and use it in GitHub Desktop.
my implementation of scala Option
package example
sealed trait OptionZ[+T] {
def map[U](f: T => U): OptionZ[U]
def flatMap[U](f: T => OptionZ[U]): OptionZ[U]
def filter(f: T => Boolean): OptionZ[T]
def foreach(f: T => Unit): Unit
}
object OptionZ {
def empty[T]: OptionZ[T] = EmptyZ
def apply[T](v: T): OptionZ[T] = SomeZ(v)
}
case object EmptyZ extends OptionZ[Nothing] {
override def map[U](f: Nothing => U): OptionZ[U] = EmptyZ
override def flatMap[U](f: Nothing => OptionZ[U]): OptionZ[U] = EmptyZ
override def filter(f: Nothing => Boolean): OptionZ[Nothing] = EmptyZ
override def foreach(f: Nothing => Unit): Unit = ()
}
final case class SomeZ[T](value: T) extends OptionZ[T] {
override def map[U](f: T => U): OptionZ[U] = SomeZ(f(value))
override def flatMap[U](f: T => OptionZ[U]): OptionZ[U] = f(value)
override def filter(f: T => Boolean): OptionZ[T] = if (f(value)) this else EmptyZ
override def foreach(f: T => Unit): Unit = f(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment