arrow-refined-types / arrow.refinement.booleans / And

And

class And<A, B> : Refined<A, B>

Boolean conjunction of the left and right predicates. left and right

In the example below we can see how we can use + to compose the predicates of arrow.refinement.numbers.PositiveInt and arrow.refinement.numbers.Even

import arrow.refinement.Refined
import arrow.refinement.numbers.PositiveInt
import arrow.refinement.numbers.Even

@JvmInline
value class PositiveEven /* private constructor */(val value: Int) {
  companion object:
    Refined<Int, PositiveEven>(::PositiveEven, PositiveInt + Even)
}

Safe nullable construction

PositiveEven.orNull(2)
// PositiveEven(value=2)
PositiveEven.orNull(1)
PositiveEven.orNull(-2)

Resolved constraints

PositiveEven.constraints(2)
// [(true, 2 should be > 0), (true, 2 should be even)]
PositiveEven.constraints(-1)
// [(false, -1 should be > 0), (false, -1 should be even)]
PositiveEven.isValid(2)
// true
PositiveEven.isValid(-1)
// false

Folding validation

PositiveEven.fold(2, { "failed: $it" }, { "success: $it" })
// success: PositiveEven(value=2)
PositiveEven.fold(-1, { "failed: $it" }, { "success: $it" })
// failed: [(false, -1 should be > 0), (false, -1 should be even)]
PositiveEven.fold(1, { "failed: $it" }, { "success: $it" })
// failed: [(false, 1 should be even)]

Unsafe require

PositiveEven.require(2)
// 2
try { PositiveEven.require(-1) } catch (e: IllegalArgumentException) { e.message }
// -1 should be > 0, -1 should be even

See Also

arrow.refinement.Refined.plus

arrow.refinement.Refined.and

Constructors

<init> Boolean conjunction of the left and right predicates. left and rightAnd(left: Refined<A, *>, right: Refined<A, B>, defaultMsg: String? = null)

Do you like Arrow?

Arrow Org
<