-3
something().orElseGet(() -> (a, b, c) -> {})
                   // ^----this part------^

where (a, b, c) is a method with a, b and c parameters. e.g: Method(a, b, c) which returns something.

My question is in practice what does this functional interface part, for me it's confusing.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
pandita
  • 43
  • 1
  • 5
  • 4
    It looks like a function that returns a function. – luk2302 Oct 13 '20 at 09:48
  • 1
    Function with no arguments returns function with three arguments that does something, but returns nothing. – loginpassword Oct 13 '20 at 09:49
  • It's a lambda returning a lambda; you could rewrite it with `{}` and `return` to see more clearly for now. – sp00m Oct 13 '20 at 09:49
  • I think you don't need now to understand what is particularly returned by `.orElseGet(..);` as you're confused with functional interfaces, lambdas, method references and etc. It's better to learn those concepts first. Then you can look up the API documentation and see what returns what. – Giorgi Tsiklauri Oct 13 '20 at 11:13

1 Answers1

3

It returns a Supplier that then supplies the three parameter method implementation (a, b, c) -> {}

Usually, all method parameters in Java are evaluated as soon as a method is called.

This means, that in the hypothetical case of orElseGet((a, b, c) -> {}) the method would always be created, whether it is needed or not. But as it is only needed when there is no other value present, having the intermediate supplier means that the method is only created when it is actually needed.

As the value that is used in the case that there is no value present might be arbitrarily costly to create, the supplier is potentially a huge time saver. In your case there will not be much of a difference (creating a supplier or creating a lambda is probably about equal in terms of cost). But there can be other situations where getting the value might involve database lookups, string concatenation etc, where it can be a huge benefit to only perform those actions when they are actually needed.

sina
  • 1,817
  • 1
  • 18
  • 42
  • 1
    In case of a lambda expression, we can say for sure that the instantiation is not costly at all. In case of a non-capturing lambda expression like `(a, b, c) -> {}`, it’s almost zero. And regardless of how costly the instantiation might be, the instantiation of the `Supplier` has the same costs, so using `orElseGet(() -> (a, b, c) -> {})` instead of `orElse((a, b, c) -> {})` saves nothing. – Holger Oct 13 '20 at 10:07
  • In this case yes. That part of the answer was meant in a more general sense, but I'll clarify. – sina Oct 13 '20 at 10:35
  • Thank you both for your answers!! – pandita Oct 14 '20 at 14:13