java21学习笔记-未命名的模式和变量 - 指南
使用未命名变量和未命名模式增强 Java 编程语言,当需要变量声明或嵌套模式但从未使用时可以使用。两者都用下划线字符 _
表示。
443: | Unnamed Patterns and Variables (Preview) java21 |
456: | Unnamed Variables & Patterns java22 |
在java21中预览,在java22中正式发布。
使用下划线字符 _
声明未命名的变量 (U+005F),以代替局部变量中局部变量的名称 declaration 语句,或 catch
子句中的异常参数,或 lambda 表达式中的 lambda 参数。
使用场景
块中的局部变量声明语句
record Point(int x, int y) { }
enum Color { RED, GREEN, BLUE }
record ColoredPoint(Point p, Color c) { }
public static void main(String[] args) {
var point = new Point(12, 34);
if (point instanceof Point(int x, _)) {
System.out.println((Point) point);
System.out.println(point.x);
System.out.println(x);
}
switch (point) {
case Point(int x, _) -> System.out.println("Hello, Point!" + x);
default -> System.out.println("default");
}
}
try-with-resources 语句的资源规范
String _age = "181";
String __ = "18";
String MAX_AGE = "118";
try (var _ = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\todo.md")) ) { // Unnamed variable
// try (var _ = new FileOutputStream(new File("")) ) { // Unnamed variable
System.out.println(_age);
System.out.println(__);
System.out.println(MAX_AGE);
} catch (FileNotFoundException _) { // Unnamed variable
System.out.println("File not found");
} catch (IOException e) {
throw new RuntimeException(e);
}
基本 for
循环的标头
for (int i = 0, _ = sideEffect(i); i < a.size(); i++) { //但是不需要sideEffect复杂方法的返回值 Unnamed variable
System.out.println(a.get(i));
}
static int sideEffect(int i) {
System.out.println("这个方法很复杂,有一大堆逻辑需要执行");
return 0;
}
增强型 for
循环的标头
Map stringStringMap = Map.of("1", "a", "2", "b", "3", "c");
Set strings = stringStringMap.keySet();
System.out.println(count(strings));
static int count(Iterable orders) {
int total = 0;
for (String _ : orders) // Unnamed variable
total++;
return total;
}
catch
块的异常参数
try (var _ = new FileOutputStream(new File("")) ) { // Unnamed variable
System.out.println(_age);
System.out.println(__);
System.out.println(MAX_AGE);
} catch (FileNotFoundException _) { // Unnamed variable
System.out.println("File not found");
} catch (IOException e) {
throw new RuntimeException(e);
}
lambda 表达式的形式参数
Map stringStringMap = Map.of("1", "a", "2", "b", "3", "c");
Set strings = stringStringMap.keySet();
strings.forEach(_ ->{System.out.println("不适用循环中的这个变量");}); // Unnamed variable
总体的大概意思就是增强写法,把不用的变量或者模式直接用"_"代替。