Quantcast
Channel: Why should Java 8's Optional not be used in arguments - Stack Overflow
Viewing all articles
Browse latest Browse all 29

Answer by Swaraj Yadav for Why should Java 8's Optional not be used in arguments

$
0
0

One more approach, what you can do is

// get your optionals firstOptional<String> p1 = otherObject.getP1();Optional<BigInteger> p2 = otherObject.getP2();// bind values to a functionSupplier<Integer> calculatedValueSupplier = () -> { // your logic here using both optional as state}

Once you have built a function(supplier in this case) you will be able to pass this around as any other variable and would be able to call it using

calculatedValueSupplier.apply();

The idea here being whether you have got optional value or not will be internal detail of your function and will not be in parameter. Thinking functions when thinking about optional as parameter is actually very useful technique that I have found.

As to your question whether you should actually do it or not is based on your preference, but as others said it makes your API ugly to say the least.


Viewing all articles
Browse latest Browse all 29

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>