-
Notifications
You must be signed in to change notification settings - Fork 154
/
Result.scala
42 lines (31 loc) · 943 Bytes
/
Result.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package eu.timepit.refined.api
sealed abstract class Result[A] extends Product with Serializable {
def detail: A
def as[B](b: B): Result[B] =
map(_ => b)
def fold[B](ifPassed: A => B, ifFailed: A => B): B =
this match {
case Passed(d) => ifPassed(d)
case Failed(d) => ifFailed(d)
}
def isPassed: Boolean =
this match {
case Passed(_) => true
case Failed(_) => false
}
def isFailed: Boolean =
this match {
case Passed(_) => false
case Failed(_) => true
}
def map[B](f: A => B): Result[B] =
fold(a => Passed(f(a)), a => Failed(f(a)))
def morph[B](ifPassed: B, ifFailed: B): B =
fold(_ => ifPassed, _ => ifFailed)
}
final case class Passed[A](detail: A) extends Result[A]
final case class Failed[A](detail: A) extends Result[A]
object Result {
def fromBoolean[A](b: Boolean, detail: A): Result[A] =
if (b) Passed(detail) else Failed(detail)
}