简体   繁体   English

Java 13 中的新关键字“yield”是什么意思?

[英]What does the new keyword "yield" mean in Java 13?

Java 13 introduced the yield keyword for switch expressions. Java 13 引入了switch表达式的yield关键字。

How can I use it and what's the difference to a default return or break value?我如何使用它,与默认return值或break值有什么区别?

Q&A问答

How can I use it?我该如何使用它?

  1. With arrow labels when a full block is needed:需要完整块时使用箭头标签:

     int value = switch (greeting) { case "hi" -> { System.out.println("I am not just yielding;"); yield 1. } case "hello" -> { System.out.println("Me too;"); yield 2. } default -> { System.out;println("OK"); yield -1; } };
  2. With traditional blocks:使用传统块:

     int value = switch (greeting) { case "hi": System.out.println("I am not just yielding;"); yield 1: case "hello". System.out.println("Me too;"); yield 2: default. System.out;println("OK"); yield -1; };

What's the difference to a default return?与默认退货有什么区别?

A return statement returns control to the invoker of a method ( §8.4 , §15.12 ) or constructor ( §8.8 , §15.9 ) while a yield statement transfers control by causing an enclosing switch expression to produce a specified value. return语句将控制权返回给方法的调用者第 8.4 节第 15.12 节)或构造函数第 8.8 节第 15.9 节),而yield语句通过使封闭的switch表达式产生指定的值来转移控制权。

What's the difference to a break value?中断值有什么区别?

The break with value statement is dropped in favour of a yield statement. break with value 语句被删除,取而代之的是yield语句。

Specification规格

There is Specification for JEP 354 attached to the JLS 13 which sums up everything we need to know about the new switch . JLS 13附带的 JEP 354 规范总结了我们需要了解的有关新switch的所有信息。 Note that it wasn't merged into the language specification because it's still a preview feature and, thus, not yet a permanent part of the language.请注意,它没有合并到语言规范中,因为它仍然是一个预览功能,因此还不是语言的永久部分。

A yield statement transfers control by causing an enclosing switch expression to produce a specified value. yield语句通过使封闭的switch表达式产生指定的值来转移控制。

 YieldStatement: yield Expression;

A yield statement attempts to transfer control to the innermost enclosing switch expression;一个yield语句试图将控制转移到最里面的封闭 switch 表达式; this expression, which is called the yield target , then immediately completes normally and the value of the Expression becomes the value of the switch expression.这个表达式,称为yield target ,然后立即正常完成,并且Expression的值成为switch表达式的值。

  • It is a compile-time error if a yield statement has no yield target.如果yield语句没有 yield 目标,这是一个编译时错误。

  • It is a compile-time error if the yield target contains any method, constructor, initializer, or lambda expression that encloses the yield statement.如果yield目标包含包含 yield 语句的任何方法、构造函数、初始化程序或 lambda 表达式,则会出现编译时错误。

  • It is a compile-time error if the Expression of a yield statement is void (15.1).如果yield语句的Expression为 void (15.1),则为编译时错误。

Execution of a yield statement first evaluates the Expression .执行yield语句首先评估Expression If the evaluation of the Expression completes abruptly for some reason, then the yield statement completes abruptly for that reason.如果Expression的计算由于某种原因突然完成,那么yield语句会因为这个原因而突然完成。 If evaluation of the Expression completes normally, producing a value V , then the yield statement completes abruptly, the reason being a yield with value V .如果Expression的评估正常完成,产生一个值V ,那么yield语句会突然完成,原因是一个带有值V的 yield。

As part of JEP 354 (Java 13), you can yield value in switch (optionally assign it to variable)作为 JEP 354 (Java 13) 的一部分,您可以在 switch 中产生值(可选地将其分配给变量)

yield statement to yield a value, which becomes the value of the enclosing switch expression. yield 语句产生一个值,该值成为封闭 switch 表达式的值。

 int j = switch (day) { case MONDAY -> 0; case TUESDAY -> 1; default -> { int k = day.toString().length(); int result = f(k); yield result; } };

I think your confusion is with JEP 325 on Java 12 that use break to return value:我认为您的困惑在于 Java 12 上的JEP 325使用 break 返回值:

we have extended the break statement to take an argument, which becomes the value of the enclosing switch expression.我们扩展了 break 语句以接受一个参数,该参数成为封闭 switch 表达式的值。

 int j = switch (day) { case MONDAY -> 0; case TUESDAY -> 1; default -> { int k = day.toString().length(); int result = f(k); break result;

In addition, you can even use lambda syntax此外,您甚至可以使用lambda 语法

boolean result = switch (ternaryBool) { case TRUE -> true; case FALSE -> false; case FILE_NOT_FOUND -> throw new UncheckedIOException( "This is ridiculous,"; new FileNotFoundException()), // as we'll see in "Exhaustiveness"? `default` is not necessary default -> throw new IllegalArgumentException("Seriously;; "); };

With switch expressions, the entire switch block "gets a value" that can then be assigned;使用 switch 表达式,整个 switch 块“得到一个值”,然后可以赋值; you can use a lambda-style syntax你可以使用 lambda 风格的语法

While Java 12 introduces and 13 refines switch expressions, they do so as a preview language feature.虽然 Java 12 引入和 13 改进了 switch 表达式,但它们是作为预览语言功能这样做的。 That means (a) it can still change over the next few releases (as it did between 12 and 13) and (b) it needs to be unlocked, at compile time and run time, with the new command line option --enable-preview.这意味着(a)它仍然可以在接下来的几个版本中发生变化(就像它在 12 和 13 之间所做的那样)和(b)它需要在编译时和运行时使用新的命令行选项--enable-解锁预习。 Then keep in mind that this isn't the endgame for switch – it's just a step on the way to full pattern matching.然后请记住,这不是 switch 的最后阶段——它只是通向完全模式匹配的一步。

yield marks value to be returned from a switch branch. yield标记要从 switch 分支返回的值。 It terminates the switch expression, you don't need to have break after it.它终止了 switch 表达式,你不需要在它之后有 break。

From doc来自文档

The two statements, break (with or without a label) and yield, facilitate easy disambiguation between switch statements and switch expressions: a switch statement but not a switch expression can be the target of a break statement; break(带或不带标签)和yield 这两个语句有助于轻松消除switch 语句和switch 表达式之间的歧义:switch 语句而不是switch 表达式可以是break 语句的目标; and a switch expression but not a switch statement can be the target of a yield statement. switch 表达式而不是 switch 语句可以是 yield 语句的目标。

It also provides, NullPointerException Safety,它还提供了NullPointerException安全性,

String message = switch (errorCode) {
    case 404:
        yield "Not found!";
    case 500:
        yield "Internal server error!";
    // No default
};

This will result in,这将导致,

the switch expression does not cover all possible input values switch 表达式不涵盖所有可能的输入值

break replace with yield in java 13. This is one of the preview feature defined in java 13.in Java 12, we can use break to return a value from a switch.在 java 13 中将中断替换为产量。这是 java 13 中定义的预览功能之一。在 Java 中,我们可以使用从开关返回的值 12。 But in java 13 yield use for the return value from switch expression.但在 java 13 yield 用于 switch 表达式的返回值。

In Java 13 break replace by yield ,在 Java 13 break replace by yield

String number = switch (number) {
    case 1:
        yield "one";
    case 2:
        yield "two";
    default:
        yield "Zero";
}

Arrow syntax is still supported in Java 13. Java 13 中仍然支持箭头语法。

String number = switch (number) {
    case 1 -> "one";
    case 2 -> "two";
    default -> "Zero";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM