Course contentsShow
← Java
Lesson 1739 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

Method Reference Type Inference

Understand how the compiler infers parameter types and return types from the target functional interface context.

Method Reference Type Inference

You'll learn: How Java automatically determines what parameter and return types a method reference needs based on where you're using it.

When you use a method reference, you're not explicitly declaring parameter types or return types—yet Java needs to know them to ensure type safety. The compiler figures this out through type inference based on the target functional interface context.

How the Compiler Infers Types

Just like with lambda expressions, the compiler looks at where you're using the method reference to determine what signature the underlying method must have:

// The compiler sees you're assigning to Function<String, Integer>
Function<String, Integer> stringLength = String::length;

// From Function<String, Integer>, it infers:
// - Input parameter type: String
// - Return type: Integer
// - So String::length must match this signature

The target type tells the compiler exactly what to expect. If String::length (which takes no parameters on the String instance and returns int) doesn't match the expected functional interface shape, you'll get a compile error.

Context Is Everything

// Target: Predicate<String> → takes String, returns boolean
Predicate<String> isEmpty = String::isEmpty;

// Target: Consumer<String> → takes String, returns void
Consumer<String> printer = System.out::println;

// Target: Supplier<List<String>> → takes nothing, returns List<String>
Supplier<List<String>> listMaker = ArrayList::new;

In each case, the functional interface on the left provides the "contract," and the compiler verifies that the method reference on the right satisfies that contract—matching parameter types and return type automatically.

Type Checking Behind the Scenes

The compiler performs the same target typing process it does with lambdas, ensuring the method signature is compatible with the abstract method of the functional interface.

Key Takeaway: Method references rely entirely on target type inference—the compiler uses the functional interface context to determine and validate parameter and return types automatically, just as it does with lambda expressions.