@@ -28,6 +28,20 @@ object Opt {
28
28
def foreach [U ](f : A => U ): Unit = self filter p foreach f
29
29
def withFilter (q : A => Boolean ): WithFilter [A ] = new WithFilter [A ](self, x => p(x) && q(x))
30
30
}
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)
31
45
}
32
46
33
47
/**
@@ -41,7 +55,8 @@ object Opt {
41
55
* Please be aware of that tradeoff.
42
56
*/
43
57
final class Opt [+ A ] private (private val rawValue : Any ) extends AnyVal with OptBase [A ] with Serializable {
44
- import Opt ._
58
+
59
+ import Opt .*
45
60
46
61
private def value : A = rawValue.asInstanceOf [A ]
47
62
@@ -140,7 +155,7 @@ final class Opt[+A] private(private val rawValue: Any) extends AnyVal with OptBa
140
155
if (isEmpty) Iterator .empty else Iterator .single(value)
141
156
142
157
@ inline def toList : List [A ] =
143
- if (isEmpty) List () else new :: (value, Nil )
158
+ if (isEmpty) List () else value :: Nil
144
159
145
160
@ inline def toRight [X ](left : => X ): Either [X , A ] =
146
161
if (isEmpty) Left (left) else Right (value)
0 commit comments