Type inference: Friend or foe?
summary
Java adds local type inference with Java 10’s var and Java 11 relaxes annotations on lambda params; inference runs at compile time so bytecode for var and explicit types is identical (no runtime overhead). Practical pitfalls: comparing().reversed() loses context -> Object so a lambda parameter type can fail to infer, using var with the diamond operator can widen List<T> to List<Object>, and var is illegal for fields and as a lambda target. Use var for local, obvious types, nested-generic clutter, and temporary debug variables; prefer explicit types when in doubt.
AI-written summary · about
chapters (12)
- 0:00Introduction and welcome
- 4:05What is type inference
- 7:14Type inference in Java over the years
- 13:39Type inference limitations in Java 8
- 22:12How type inference works with context
- 28:07Introducing the var keyword in Java 10
- 35:15Caveats and pitfalls of type inference
- 47:57Benefits of using type inference
- 59:11Targeted intersection types with var
- 1:03:12Type inference for lambda parameters in Java 11
- 1:06:52Recommendations and best practices
- 1:09:41Type inference: friend or foe?
