Last active
December 31, 2015 17:09
-
-
Save XuefengWu/8018043 to your computer and use it in GitHub Desktop.
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
/** | |
* Algebraic Data Type (ADT) for results that the business layers return to controllers. | |
* It has two cases: | |
* <ul> | |
* <li> OKResult wrapping a value | |
* <li> FailedResult containing a discriminator value and a list of error messages. | |
* <ul> | |
* Author: https://github.com/kenbot | |
*/ | |
sealed trait BusinessResult[+A] { | |
def ok: Boolean | |
def map[B](f: A => B): BusinessResult[B] | |
def flatMap[B](f: A => BusinessResult[B]): BusinessResult[B] | |
def getOrElse[B >: A](other: B): B | |
def failedAs(errorCode: ErrorCode): Boolean | |
} | |
case class OKResult[+A](result: A) extends BusinessResult[A] { | |
def ok: Boolean = true | |
def map[B](f: A => B): BusinessResult[B] = OKResult(f(result)) | |
def flatMap[B](f: A => BusinessResult[B]): BusinessResult[B] = f(result) | |
def getOrElse[B >: A](other: B): B = result | |
def failedAs(errorCode: ErrorCode): Boolean = false | |
} | |
case class FailedResult(errorCode: ErrorCode, messages: String*) extends BusinessResult[Nothing] { | |
def ok: Boolean = false | |
def map[B](f: Nothing => B): BusinessResult[B] = this | |
def flatMap[B](f: Nothing => BusinessResult[B]): BusinessResult[B] = this | |
def getOrElse[B](other: B): B = other | |
def failedAs(code: ErrorCode): Boolean = (errorCode == code) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment