Types, errors and modern syntax · core
Lambdas, functional interfaces and Optional
A lambda supplies the one abstract method of a functional interface. Lambdas capture values, not variables. Optional is for return values, not for fields.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- A functional interface has exactly one abstract method.
@FunctionalInterfaceis optional but makes the compiler check it. - Built-ins: Function, BiFunction, Supplier (no input), Consumer (no output), Predicate (boolean), UnaryOperator, BinaryOperator.
- Comparator counts as functional:
compareis its only abstract method. - Lambdas capture values, not variables. A local variable might be gone or changed by another thread when the lambda runs, so it must be effectively final.
- Inside a lambda
thisis the enclosing object. Inside an anonymous class it is the anonymous object. - Checked exceptions in lambdas: catch and wrap (UncheckedIOException), or use a loop.
- Optional:
orElse(x)evaluates x every time, even when a value exists. UseorElseGet(() -> ...)for expensive defaults.orElseThrow(...)replacesget(). - Do not use Optional as a field or parameter: it is not Serializable, the field can still be null, and it confuses JSON and JPA mappers. Never return null from a method that returns Optional.
Optional.of(null)throws; useofNullable.isPresent()followed byget()is a sign to use map, flatMap or orElseThrow.
The red pen
Common traps: mistake → fix
Mistake: orElse(call()) calls call() only when empty
Fix: the argument is always evaluated; use orElseGet.
Mistake: A lambda can change a local counter
Fix: locals must be effectively final; use a stream operation or an atomic.
Mistake: Optional fields are good style
Fix: use Optional for return values only.
Easy to hard
Questions interviewers ask, easy to hard
- What is a functional interface?
- Why must a variable used in a lambda be effectively final?
- What is wrong with
repo.findById(id).get()? - Difference between orElse and orElseGet?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.