abstract class Result[+A, +B] {
def getGood: A = this match {
case Good( a ) => a
case _ => throw new java.util.NoSuchElementException("this instance is not Good")
}
def getBad: B = this match {
case Bad( b ) => b
case _ => throw new java.util.NoSuchElementException("this instance is not Bad")
}
def get: A = getGood
def getOrElse[AA >: A]( a: => AA ): AA = this match {
case Good( a ) => a
case _ => a
}
def orElse[AA >: A, BB >: B]( r: => Result[AA, BB] ): Result[AA, BB] = this match {
case Good( a ) => Good( a )
case _ => r
}
def exists( f: A => Boolean ): Boolean = this match {
case Good( a ) => f( a )
case _ => false
}
def forall( f: A => Boolean ): Boolean = this match {
case Good( a ) => f( a )
case _ => false
}
def foreach( f: A => Unit ): Unit = this match {
case Good( a ) => f( a )
case _ => ()
}
def filter( f: A => Boolean ): Result[A, B] = this match {
case Good( a ) => if( f( a ) ) Good( a ) else Empty
case Bad( b ) => Bad( b )
case _ => Empty
}
def flatMap[C, BB >: B]( f: A => Result[C, BB] ): Result[C, BB] = this match {
case Good( a ) => f( a )
case Bad( b ) => Bad( b )
case _ => Empty
}
def map[C]( f: A => C ): Result[C, B] = this match {
case Good( a ) => Good( f(a) )
case Bad( b ) => Bad( b )
case _ => Empty
}
def >>= [C, BB >: B] ( f: A => Result[C, BB] ): Result[C, BB] = flatMap( f )
def >> [C, BB >: B] ( f: => Result[C, BB] ): Result[C, BB] = flatMap( _ => f )
def >>-[C]( f: A => C ): Result[C, B] = map( f )
def toOption: Option[A] = this match {
case Good( a ) => Some( a )
case _ => None
}
def toList: List[A] = this match {
case Good( a ) => List( a )
case _ => Nil
}
def toBoolean: Boolean = this match {
case Good( _ ) => true
case _ => false
}
}
case class Good[+A, +B]( a: A ) extends Result[A, B]
case class Bad[+A, +B]( b: B ) extends Result[A, B]
case object Empty extends Result[Nothing, Nothing]
|