Skip to content

Commit

Permalink
Added first version of the TryRaise
Browse files Browse the repository at this point in the history
  • Loading branch information
rcardin committed Apr 12, 2024
1 parent e4680aa commit 842bf25
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/scala/in/rcard/raise4s/Builders.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package in.rcard.raise4s

import scala.util.{Failure, Success, Try}

/** Runs a computation `block` using [[Raise]], and return its outcome as [[Either]].
* - [[Right]] represents success,
* - [[Left]] represents logical failure.
Expand Down Expand Up @@ -40,3 +42,22 @@ def option[A](block: OptionRaise ?=> A): Option[A] =
_ => None,
Some(_)
)

class TryRaise(val raise: Raise[Throwable]) extends Raise[Throwable]:
override def raise(error: Throwable): Nothing = raise.raise(error)

object TryPredef:
extension [A](tryValue: Try[A])(using tryRaise: TryRaise)
def bind(): A = tryValue match
case Success(a) => a
case Failure(e) => tryRaise.raise(e)

def $try[A](block: TryRaise ?=> A): Try[A] =
fold(
{
given tryRaise: TryRaise = new TryRaise(new DefaultRaise())
block(using tryRaise)
},
Failure(_),
Success(_)
)

0 comments on commit 842bf25

Please sign in to comment.