Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we adopt Booleans to Java8 like Optionals (ifPresent and orElse)

Using Java8, this could be done:

Optional.ofNullable(realResult).orElse(mockResult);

instead of:

if(realResult == null)
    return mockResult;
return realResult;

Question: Could we adobt Booleans to java8? or in other words, can we write something like that:

Boolean.valueOf(boolVar).ifTrue(trueResult).orElse(falseResult);

instead of:

if(boolVar)
    return trueResult;
return falseResult;

Edit #1 Thanks for suggesting ternary operations, still wondering if we can?

like image 454
Ahmed Ghoneim Avatar asked Nov 02 '25 11:11

Ahmed Ghoneim


1 Answers

How about using the terniary operator that's already included in the language?

boolVar ? trueResult : falseResult

EDIT: that's how it would look like if you really want such a class:

public class Conditional<T> {

    private final boolean condition;
    private T valueWhenTrue;

    public static Conditional valueOf(boolean condition) {
        return new Conditional(condition);
    }

    private Conditional(boolean condition) {
        this.condition = condition;
    }

    public Conditional ifTrue(T valueWhenTrue) {
        this.valueWhenTrue = valueWhenTrue;
        return this;
    }

    public T orElse(T valueWhenFalse) {
        return condition ? valueWhenTrue : valueWhenFalse;
    }
}

Usage:

Conditional.valueOf(boolVar).ifTrue(trueResult).orElse(falseResult)
like image 149
Peter Walser Avatar answered Nov 04 '25 01:11

Peter Walser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!