DEV Community

Discussion on: How to Make Your Reviewer Cry Using Java Optional

Collapse
joshuakb2 profile image
Joshua Baker

This line could be made simpler:

System.out.println("The number is: " + number.orElseGet(() -> alternativeNumber()));
Enter fullscreen mode Exit fullscreen mode

is equivalent to

System.out.println("The number is: " + number.orElseGet(alternativeNumber));
Enter fullscreen mode Exit fullscreen mode
Collapse
dante0747 profile image
Majid Abarghooei Author

Hi Joshua. I don't think so; It faces a compile error.

Collapse
thegoncalomartins profile image
Gonçalo Martins • Edited on

Not like you described, but like this

System.out.println("The number is: " + number.orElseGet(NameOfTheClass::alternativeNumber));
Enter fullscreen mode Exit fullscreen mode

With method reference.

If the method was not static and was an instance one, then it would be like this

System.out.println("The number is: " + number.orElseGet(this::alternativeNumber));
Enter fullscreen mode Exit fullscreen mode