<div dir="ltr"><div style="font-family:monospace" class="gmail_default">Hello all,<br><br>I have an idea that I want to run by you all -- a new method on java.util.function.Function to capture ternary operations.<br><br>Here is a mockup of what I wanted to do.<br><br>> <br>> import java.util.function.Function;<br>> <br>> @FunctionalInterface<br>> public interface Function2<I, O> extends Function<I, O><br>> {<br>> <br>>    public static <I, O> Function<I, O> ternary<br>>    (<br>>        Predicate<I> test,<br>>        Function<I, O> trueOutput,<br>>        Function<I, O> falseOutput<br>>    )<br>>    {<br>>    <br>>       return<br>>           (I input) -><br>>               test.test(input)<br>>               ? trueOutput.apply(input)<br>>               : falseOutput.apply(input)<br>>               ;<br>>    <br>>    }<br>> <br>> }<br>> <br><br>I think this is useful for a few reasons.<br><br> * This composes, just like the ternary operator itself.<br> <br> * It pairs well with Function.identity() and method references to clearly (but concisely) communicate intent.<br> <br> * Ternary operations are common, so this will find great use by developers of all sorts.<br><br>There is at least one part I don't quite like about this design - what if one (or both!) of your outputs is not a functional transformation of the input?<br><br>For example, String username = id.isBlank() ? "UNKNOWN" : lookup(id);<br><br>Obviously, this is easy to work around - simply ignore the input of the function. But you lose clarity and simplicity that way. I would put a note in the javadoc that says that this method should only be used in instances where both outputs are a functional transformation of the input. That way, intent is clarified. But if we go that route, maybe this function should get a better name to capture that? testThenApply? ternaryTransform? ternaryApply?<br><br>Thank you for your time and help!<br>David Alayachew<br></div></div>