Java.Core.Why we can assign greeting::length to Supplier

We can assign greeting::length to Supplier<Integer> because their method signatures match.


🔗 Let’s Compare the Signatures

Supplier Functional Interface

@FunctionalInterface
public interface Supplier<T> {
    T get();
}
  • Method signature: Integer get()

Method Reference — greeting::length

public int length()
  • This method belongs to String, and greeting is a specific String object.
  • It takes no arguments and returns int (which gets autoboxed to Integer).

✅ Matching the Signature

Expected (Supplier<Integer>)Actual (greeting::length)Matching?
Integer get()int length()✔️ Yes (autoboxed to Integer)

📣 Key Rule for Method References

Method Reference = Allowed only if it fits the target functional interface’s method signature.

This is why:

Supplier<Integer> bound = greeting::length;  // Works

But this would fail:

Function<String, Integer> func = greeting::length;  // ❌ Doesn't match Function<T, R>

🔥 Pro Tip for Interviews

✅ When asked “Why does this work?”, just say:

“The method reference fits the functional interface’s method signature.”

This entry was posted in Без рубрики. Bookmark the permalink.