2
\$\begingroup\$

I have written an Optional type in groovy roughly based on java8s Optional. I implemented and use a fold method and would like to know if it can be improved. First, here comes the Optional (I will only use its fold method for my question though):

class Optional<T> {
    T value

    private Opional(T value) {
        this.value = value
    }

    final Boolean isPresent() {
        value != null
    }

    final Object map(Closure mapper) {
        mapper(value).with { Object result ->
            if (result != null)
                return new Optional(result)
            else
                return new Optional(null)
        }
    }

    final Object flatMap(Closure mapper) {
        if( ! this.isPresent)
            return Optional.empty()
        else
            return this.map(mapper)
    }

    public Object fold(Closure ifEmpty, Closure f) {
        if(isPresent())
            return ifEmpty.call()
        else
            return f.call(value)

    }

    final static Optional<T> of(T value) {
        if(value == null)
            throw new IllegalArgumentException("Argument for Optional.of() must not be null")

        new Optional<T>(value)
    }

    final static Optional<T> empty() {
        new Optional(null)
    }
}

(I ommitted some methods like orElse and others)

Next, there are maybe two result-variables. They are therefore of type Optional. I want to execute an action if at least one of the result variables is present AND successfull. I do it like that:

if( resultA.fold({false}, {it.isSuccess()}) || resultB.fold({false}, {it.isSuccess()}) ) {
    //execute action
}

Is it a good way to use fold here or should I just stay with:

 (resultA.isPresent() && resultA.isSuccess())

Also, can/could this usage of fold be improved or are there other ways to work it out?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.