Is there a Java equivalent to C#'s 'yield' keyword?

前端 未结 6 1114
自闭症患者
自闭症患者 2020-11-27 11:36

I know there is no direct equivalent in Java itself, but perhaps a third party?

It is really convenient. Currently I\'d like to implement an iterator that yields all

6条回答
  •  鱼传尺愫
    2020-11-27 12:10

    I know it's a very old question here, and there are two ways described above:

    • bytecode manipulation that's not that easy while porting;
    • thread-based yield that obviously has resource costs.

    However, there is another, the third and probably the most natural, way of implementing the yield generator in Java that is the closest implementation to what C# 2.0+ compilers do for yield return/break generation: lombok-pg. It's fully based on a state machine, and requires tight cooperation with javac to manipulate the source code AST. Unfortunately, the lombok-pg support seems to be discontinued (no repository activity for more than a year or two), and the original Project Lombok unfortunately lacks the yield feature (it has better IDE like Eclipse, IntelliJ IDEA support, though).

提交回复
热议问题