Skip to content

Commit

Permalink
Introduced the 'ensure' and 'ensureNotNull' functions
Browse files Browse the repository at this point in the history
  • Loading branch information
rcardin committed Apr 9, 2024
1 parent 0b6e2f3 commit 6cf95ab
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/main/scala/in/rcard/raise4s/Builders.scala
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
package in.rcard.raise4s

/** Runs a computation `block` using [[Raise]], and return its outcome as [[Either]].
* - [[Right]] represents success,
* - [[Left]] represents logical failure.
*
* This function re-throws any exceptions thrown within the [[Raise]] block.
*
* @param block A computation that can raise errors of type `Error`
* @tparam A The type of the value returned by the computation
* @tparam Error The type of the logical error that can be raised by the computation
* @return An [[Either]] representing the outcome of the computation
*/
def either[A, Error](block: Raise[Error] ?=> () => A): Either[Error, A] =
fold(block, error => Left(error), value => Right(value))
9 changes: 8 additions & 1 deletion src/main/scala/in/rcard/raise4s/Raise.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ package in.rcard.raise4s

trait Raise[-Error]:
def raise(e: Error): Nothing

infix type raises[R, Error] = Raise[Error] ?=> R

def raise[Error](e: Error)(using raise: Raise[Error]): Nothing = raise.raise(e)

def ensure[Error](condition: Boolean, raise: () => Error)(using r: Raise[Error]): Unit =
if !condition then r.raise(raise())

def ensureNotNull[B, Error](value: B, raise: () => Error)(using r: Raise[Error]): B =
if value == null then r.raise(raise())
else value
12 changes: 12 additions & 0 deletions src/test/scala/in/rcard/raise4s/RaiseSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package in.rcard.raise4s

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class RaiseSpec extends AnyFlatSpec with Matchers {

"ensureNotNull" should "return the value if it is not null" in {
// TODO: Implement the test
true should be(true)
}
}

0 comments on commit 6cf95ab

Please sign in to comment.