闭包“指令"的含义和用途是什么?

编程入门 行业动态 更新时间:2024-10-25 08:18:17
本文介绍了闭包“指令"的含义和用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在文档和Closure.java中看到对指令"的引用,而没有解释它是什么或它的用途,

I see in the docs and in Closure.java references to "directive" with no explanation of whgat it is or what it is for,

public static final int DONE = 1, SKIP = 2; private int directive; /** * @return Returns the directive. */ public int getDirective() { return directive; } /** * @param directive The directive to set. */ public void setDirective(int directive) { this.directive = directive; }

我也在Google上进行了搜索,但除了其中出现的一些测试之外,我没有找到任何对其的引用

I also googled it but I found not a single reference to it, except from some tests where it appears

assert directive = DONE

所以我唯一知道的是它可以完成或跳过.

so the only thing I know is that it can be DONE or SKIP.

有没有这种现实生活"的例子?

Is there any "real life" example of this?

推荐答案

此指令属性在groovy运行时内部用作收集操作中的循环中断条件参见groovy源代码中的 groovy.runtime.DefaultGroovyMethods.java :

This directive property is used internally from the groovy runtime as a loop break condition in collect operations see groovy.runtime.DefaultGroovyMethods.java in groovy source code:

public static <T,E> Collection<T> collect(Collection<E> self, Collection<T> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends T> transform) { for (E item : self) { collector.add(transform.call(item)); if (transform.getDirective() == Closure.DONE) { break; } } return collector; }

它可以通过Groovy运行时中的getter和setter getDirective()和setDirective()访问并通过脚本中闭包的 directive 属性

It is accessible via the getter and setter getDirective() and setDirective() in groovy runtime and via the directive property of the closure in your script.

完成用于停止收集操作

例如在5点后停止:

(1..10).collect { if (it>= 5) directive = Closure.DONE; new Tuple(it, (int)(it/2) ) } Result: [[1, 0], [2, 1], [3, 1], [4, 2], [5, 2]]

SKIP 未使用...对收集操作没有影响(?!)

SKIP is not used ... and has no effect on the collect operation (?!)

在某些特殊情况下,此功能听起来有点像个把戏最好使用诸如find,findAll等收集方法.如果可能的话

This feature sounds a bit like a trick for special cases it is probably better to use collection methods like find, findAll etc. if possible

更多推荐

闭包“指令"的含义和用途是什么?

本文发布于:2023-11-25 17:24:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指令   含义   用途   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!