Created
December 9, 2021 05:31
-
-
Save gcnyin/f0eb40816e696769ea8e93d7b69aa58a to your computer and use it in GitHub Desktop.
my implementation of scala Option
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
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