闭包“指令"的含义和用途是什么? [英] What is and what's the use of the Closure "directive"

查看:56
本文介绍了闭包“指令"的含义和用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档和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

这篇关于闭包“指令"的含义和用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆