Java 22 未命名变量与模式匹配:优雅代码的新范式
Java 22 Unnamed Variables and Patterns: A New Paradigm for Elegant Code
| iDev PR | 2026-08-30T09:21:41
详解 Java 22 正式引入的未命名变量和未命名模式特性,展示如何通过这些新语法减少样板代码并提升可读性。
A detailed guide to Java 22's officially introduced unnamed variables and unnamed patterns features, showing how these new syntax elements reduce boilerplate and improve readability.
告别无用变量Java 22 正式将未命名变量(Unnamed Variables)和未命名模式(Unnamed Patterns)从预览特性转为正式特性。这一变化虽然看似微小,却能显著提升日常编码的优雅性。未命名变量的使用场景在 Java 中,我们经常需要声明一些实际上并不使用的变量。典型场景包括:try-catch 中不需要引用的异常对象:catch (Exception _)增强 for 循环中只需要计数不需要元素值的场景:for (var _ : list)Lambda 表达式中不使用的参数:(_, value) -> process(value)模式匹配中不关心的组件:case Point(var x, _) -> handleX(x)与 switch 模式匹配的结合未命名模式在 switch 表达式的模式匹配中特别强大。当我们需要匹配某个类型但不关心其组件时,可以直接使用下划线占位。这在处理复杂的密封类层次结构时尤为有用。实际收益在 iDev 团队的实践中,引入未命名变量后:消除了编译器关于未使用变量的警告,代码更加整洁在 Stream 操作中,Lambda 的意图更加清晰模式匹配的 switch 语句简洁了约 20%注意事项未命名变量不能用于局部变量声明的初始化赋值,也不能在后续代码中引用。它的本质是向编译器和代码阅读者传达明确信号:这个值是有意忽略的,而非遗忘。建议团队在编码规范中明确规定未命名变量的使用场景,保持一致性。
Goodbye to Unused VariablesJava 22 has officially graduated unnamed variables and unnamed patterns from preview to production features. While this change may seem minor, it significantly improves the elegance of everyday coding.Use Cases for Unnamed VariablesIn Java, we frequently need to declare variables that are never actually used. Typical scenarios include:Exception objects not referenced in try-catch: catch (Exception _)Enhanced for loops needing only count, not element values: for (var _ : list)Unused parameters in Lambda expressions: (_, value) -> process(value)Irrelevant components in pattern matching: case Point(var x, _) -> handleX(x)Combining with Switch Pattern MatchingUnnamed patterns are particularly powerful in switch expression pattern matching. When we need to match a type but don't care about its components, we can directly use underscore placeholders. This is especially useful when dealing with complex sealed class hierarchies.Practical BenefitsIn iDev team's practice, after introducing unnamed variables:Eliminated compiler warnings about unused variables, resulting in cleaner codeLambda intent in Stream operations became clearerPattern matching switch statements became approximately 20% more conciseCaveatsUnnamed variables cannot be used in local variable declaration initializations, nor can they be referenced in subsequent code. Their essence is to send a clear signal to both the compiler and code readers: this value is intentionally ignored, not forgotten. Teams should explicitly define use cases for unnamed variables in their coding standards for consistency.