0

I have this issue that to me seems strange:

Person p = null;

Supplier<String> s = p::getName; // Throws NPE immediately

Supplier<String> s2 = () -> p.getName();
s2.get(); // Throws NPE after get() call

How come both s and s2 are Suppliers, yet work so differently?

I'd expect s to throw NPE after calling s.get(), not immediately.

Why is that? What's happening here?

Thanks!

Patryk Krawczyk
  • 1,342
  • 1
  • 14
  • 25
  • Consider also the difference between `methodReturningAPerson()::getName` and `() -> methodReturningAPerson().getName()`: the former invokes `methodReturningAPerson()` once; the latter invokes it every time the supplier is invoked. – Andy Turner Mar 20 '19 at 14:43
  • Sorry for duplicating, couldn't find a good thread on SO. – Patryk Krawczyk Mar 20 '19 at 14:44
  • It's not an especially easy thing to search for (my search for [site:stackoverflow.com java npe method reference supplier](https://www.google.com/search?q=site%3Astackoverflow.com+java+npe+method+reference+supplier) didn't show up this result in the first page). – Andy Turner Mar 20 '19 at 14:45

0 Answers0