@@ -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 */
4357final 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)
0 commit comments