ProgrammingJava Developer

Explain how lambda expressions and functional interfaces work in Java. What errors can occur with their improper use?

Pass interviews with Hintsage AI assistant

Answer

Lambda expressions were introduced in Java 8 for a more concise syntax for implementing single-method interfaces (functional interfaces).

A functional interface is an interface with exactly one abstract method. Example:

@FunctionalInterface interface MyAction { void perform(String s); }

A lambda expression allows you to implement such an interface:

MyAction action = (s) -> System.out.println(s); action.perform("Hello lambda!");

When using a lambda expression, the compiler understands which interface is implemented (target typing). Lambdas are often used with collections:

List<String> list = Arrays.asList("one", "two", "three"); list.forEach(s -> System.out.println(s));

Trick Question

Question: Can a lambda expression refer to non-static fields or methods of an outer class? What are the limitations in this regard?

Answer: A lambda expression can refer to fields and methods of the outer class, but if it uses local variables from the outer method, those variables must be final or effectively final (i.e., not changed after the first assignment). For example:

void doIt() { int x = 42; Runnable r = () -> System.out.println(x); // x must be effectively final }

If x is modified after declaration, a compilation error will occur.

Examples of Real Errors Due to Ignorance of Nuances


Story

While using a lambda inside a method, there was an attempt to modify an outer local variable, leading to a compilation error "Variable used in lambda expression should be final or effectively final". Developers spent a lot of time looking for the cause until they recalled this limitation.


Story

In one project, custom interfaces for lambdas were used, but they forgot to annotate them with @FunctionalInterface. After refactoring, a second method was added to the interface, and the project stopped compiling. This caused unexpected errors that were difficult to catch.


Story

An attempt to serialize an object containing a field with a lambda expression led to serialization/deserialization not working correctly—lambdas are not serialized by default. It is important to remember that if a lambda contains inconsistent dependencies, errors will occur when transmitted over the network.