I'm stuck trying to pass Optional.toJavaUtil()
as method reference to a map
method (either Optional.map()
and Stream.map()
).
The simplified example of my code:
aLegacyService.getGuavaOptional()
.toJavaUtil()
.map(MyPojo::getAnotherGuavaOptional)
.flatMap(Optional::toJavaUtil); // <-- This doesn't compile
The compiler gives me a cryptic error:
Error:(177, 72) java: invalid method reference
non-static method toJavaUtil() cannot be referenced from a static context
I think the reason is that there are 2 methods: instance method and static method, both with the same name. If I use lambda syntax, both variants work fine:
.flatMap(opt -> opt.toJavaUtil()) // This is OK
// and
.flatMap(opt -> Optional.toJavaUtil(opt)); // Also OK
Q: Is there a way to make this work with method reference? (e.g. by somehow specifying which of two methods I want to use?)