Campbell Ritchie wrote:Please remind us all why orElseThrow(XYZException::new) is better than orElseThrow(new XYZException()). I remember reading about that in Ken Kousen's book, and I think I know the answer.
I think Ken's book probably addresses a different question, since the second code isn't even an option in the real world. I can think of two variants that might have been worth discussing:
1. Why isn't orElseThrow(Throwable) provided as an option in the API?
2. Is there a reason to prefer orElseThrow(XYZException::new) instead of orElseThrow(() -> new XYZException())?
The first one was addressed by Stephan: it would require us to create the exception (and populate its stack trace, a somewhat time-consuming operation) whether or not anything actually went wrong. That could potentially degrade performance for no good reason. We don't want to create an exception unless we actually need it.
The second one is probably what Ken was talking about in his book. In situations where we can use either a lambda expression or a method handle, is there any reason to prefer one or the other? A lambda expression is more flexible, of course - you have more freedom to write arbitrary code into the expression. Within some limits, of course. I think the main benefit of using a method is performance... though I'm not sure how big a difference it really makes. When you use a lambda expression, the compiler generates methods and/or nested class to contain the implementation. Whereas if you use a method reference, it has the ability to calls the already-existing method more directly. I'm not sure if there are any other benefits, though.