File tree Expand file tree Collapse file tree 3 files changed +39
-0
lines changed Expand file tree Collapse file tree 3 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -3,5 +3,6 @@ package optional
33import "errors"
44
55var (
6+ ErrNilFunction = errors .New ("nil function" )
67 ErrNoSuchValue = errors .New ("no such value" )
78)
Original file line number Diff line number Diff line change @@ -120,6 +120,20 @@ func (opt *Optional[T]) IsPresent() bool {
120120 return opt .val != nil
121121}
122122
123+ // Or returns the Optional instance if the value is present, otherwise returns an Optional produced
124+ // by the supplying function.
125+ func (opt * Optional [T ]) Or (supplier func () * Optional [T ]) * Optional [T ] {
126+ if supplier == nil {
127+ panic (ErrNilFunction )
128+ }
129+
130+ if opt .IsPresent () {
131+ return opt
132+ }
133+
134+ return supplier ()
135+ }
136+
123137// OrElse returns the value if present, otherwise returns other.
124138func (opt * Optional [T ]) OrElse (other T ) T {
125139 if opt .IsEmpty () {
Original file line number Diff line number Diff line change @@ -227,6 +227,30 @@ func TestOptionalIsEmpty(t *testing.T) {
227227 a .NotTrueNow (opt .IsEmpty ())
228228}
229229
230+ func TestOptionalOr (t * testing.T ) {
231+ a := assert .New (t )
232+
233+ opt := optional.New [string ](nil )
234+ a .PanicOfNow (func () {
235+ opt .Or (nil )
236+ }, optional .ErrNilFunction )
237+
238+ out := opt .Or (func () * optional.Optional [string ] { return optional .Of ("or value" ) })
239+ a .NotNilNow (out )
240+ a .TrueNow (out .IsPresent ())
241+ a .NotPanicNow (func () {
242+ a .EqualNow (out .GetPanic (), "or value" )
243+ })
244+
245+ opt = optional .Of ("Hello world" )
246+ out = opt .Or (func () * optional.Optional [string ] { return optional .Of ("or value" ) })
247+ a .NotNilNow (out )
248+ a .TrueNow (out .IsPresent ())
249+ a .NotPanicNow (func () {
250+ a .EqualNow (out .GetPanic (), "Hello world" )
251+ })
252+ }
253+
230254func TestOptionalOrElse (t * testing.T ) {
231255 a := assert .New (t )
232256
You can’t perform that action at this time.
0 commit comments