<< 在 groovy 中是什么意思

What does << mean in groovy

我正在尝试阅读一些 groovy 并在几个上下文中遇到了 "double less than" <<。很难google。它在这些示例中是如何工作的?

new URL('the url').withInputStream{ i -> f.withOutputStream{ it << i }}

在Gradle中:

task hello << {
  println 'Hello world!'
}

在常规 Java 中(以及几乎任何其他地方),这意味着数字左移:

assert (1<<4)==16

但是 Groovy 允许 overloading operators 并且在提到的示例中它是指,它被重载的内容(使用方法 a.leftShift(b))。与 C++ 一样,它通常用于指示 "append" 操作(例如 std::cout << "Hello World" << std::endl)。

在上面的示例中,它表示 "append the stream"(参见 https://github.com/groovy/groovy-core/blob/GROOVY_2_4_X/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java#L113) or "add this functionality/closure to the task" (see https://github.com/gradle/gradle/blob/RB_2.0/subprojects/core/src/main/groovy/org/gradle/api/internal/AbstractTask.java#L460)。

还有例如<< 将项目附加到常规列表(例如 def list = []; list << 42)。

如果你想自己使用它,你基本上可以用它做任何事情。在下面的例子中 "add five to cnt"

class X {
    def cnt = 0
    def leftShift(x) {
        cnt += 5
    }
}

def x = new X()
x << "lol"
assert x.cnt == 5

是聪明吗?也许不吧。您很可能会添加经常需要且对操作员有意义的功能。并注意 << 运算符的优先级!