Skip to content

Commit e630f64

Browse files
authoredApr 10, 2024··
Merge pull request #560 from AVSystem/opt-when
Add `Opt.when` method
2 parents ca514b8 + 706793c commit e630f64

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed
 

‎core/src/main/scala/com/avsystem/commons/misc/Opt.scala

+17-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,20 @@ object Opt {
2828
def foreach[U](f: A => U): Unit = self filter p foreach f
2929
def withFilter(q: A => Boolean): WithFilter[A] = new WithFilter[A](self, x => p(x) && q(x))
3030
}
31+
32+
final class LazyOptOps[A](private val opt: () => Opt[A]) extends AnyVal {
33+
/** When a given condition is true, evaluates the `opt` argument and returns it.
34+
* When the condition is false, `opt` is not evaluated and `Opt.Empty` is
35+
* returned.
36+
*/
37+
def when(cond: Boolean): Opt[A] = if (cond) opt() else Opt.Empty
38+
/** Unless a given condition is true, this will evaluate the `opt` argument and
39+
* return it. Otherwise, `opt` is not evaluated and `Opt.Empty` is returned.
40+
*/
41+
@inline def unless(cond: Boolean): Opt[A] = when(!cond)
42+
}
43+
44+
implicit def lazyOptOps[A](opt: => Opt[A]): LazyOptOps[A] = new LazyOptOps(() => opt)
3145
}
3246

3347
/**
@@ -41,7 +55,8 @@ object Opt {
4155
* Please be aware of that tradeoff.
4256
*/
4357
final class Opt[+A] private(private val rawValue: Any) extends AnyVal with OptBase[A] with Serializable {
44-
import Opt._
58+
59+
import Opt.*
4560

4661
private def value: A = rawValue.asInstanceOf[A]
4762

@@ -140,7 +155,7 @@ final class Opt[+A] private(private val rawValue: Any) extends AnyVal with OptBa
140155
if (isEmpty) Iterator.empty else Iterator.single(value)
141156

142157
@inline def toList: List[A] =
143-
if (isEmpty) List() else new ::(value, Nil)
158+
if (isEmpty) List() else value :: Nil
144159

145160
@inline def toRight[X](left: => X): Either[X, A] =
146161
if (isEmpty) Left(left) else Right(value)

‎core/src/test/scala/com/avsystem/commons/misc/OptTest.scala

+12
Original file line numberDiff line numberDiff line change
@@ -66,4 +66,16 @@ class OptTest extends AnyFunSuite {
6666
val seq: Seq[Int] = Opt(5).mapOr(Nil, i => 0 until i)
6767
assert(seq == (0 until 5))
6868
}
69+
70+
test("Opt.{when, unless}") {
71+
val opt = Opt(42)
72+
73+
assert(opt.when(true) == opt)
74+
assert(opt.when(false) == Opt.Empty)
75+
assert(Opt(fail("Parameter should not be evaluated")).when(false) == Opt.Empty)
76+
77+
assert(opt.unless(false) == opt)
78+
assert(opt.unless(true) == Opt.Empty)
79+
assert(Opt(fail("Parameter should not be evaluated")).unless(true) == Opt.Empty)
80+
}
6981
}

0 commit comments

Comments
 (0)
Please sign in to comment.