gradle: `fileCollection.plus()`返回ArrayList,与接口相矛盾

huangapple go评论136阅读模式
英文:

gradle: fileCollection.plus() returns ArrayList contradicting interface

问题

gradle: fileCollection.plus() 返回 ArrayList 与接口相矛盾。

def foo = files([]);  // foo: gradle FileCollection
println foo.class
foo = foo.plus(sourceSets.main.java.srcDirs);    // foo: java.util.ArrayList
println foo.class

但它应该返回一个 FileCollection:

https://docs.gradle.org/current/javadoc/org/gradle/api/file/FileCollection.html#plus-org.gradle.api.file.FileCollection-

英文:

gradle: fileCollection.plus() returns ArrayList contradicting interface.

def foo = files([]);  // foo: gradle FileCollection
println foo.class
foo = foo.plus(sourceSets.main.java.srcDirs);    // foo: java.util.ArrayList
println foo.class

But it should return a FileCollection:

https://docs.gradle.org/current/javadoc/org/gradle/api/file/FileCollection.html#plus-org.gradle.api.file.FileCollection-

答案1

得分: 1

The plus方法被重载了,你正在查看错误的版本。

你链接的FileCollection.plus的API具有以下签名:

FileCollection plus​(FileCollection collection)

返回一个包含此集合和给定集合的并集的FileCollection。返回的集合是动态的,并跟踪两个源集合的更改。

但你传递的是一个ArrayList作为参数。ArrayList不是FileCollection

然而,FileCollection也是一个Iterable,所以你实际调用的是标准的Groovy方法Interable.plus,具有以下签名:

public Collection plus(Iterable right)

创建一个由两个可迭代对象组成的集合的并集。如果左边的可迭代对象是一个Set,那么返回的集合将是一个Set,否则是一个List。这个操作总是会为结果创建一个新对象,而操作数保持不变。

因为“左边”的可迭代对象不是一个Set(它是一个FileCollection),所以你得到的是一个List,Groovy恰好在实现中使用了ArrayList

英文:

The plus method is overloaded, and you are looking at the wrong one.

The API for FileCollection.plus that you linked to has the signature:

> FileCollection plus​(FileCollection collection)
>
> Returns a FileCollection which contains the union of this collection and the given collection. The returned collection is live, and tracks changes to both source collections.

But you are passing an ArrayList as the parameter. An ArrayList is not a FileCollection.

However, a FileCollection is also an Iterable, so what you are really invoking is the standard Groovy method Interable.plus with this signature:

> public Collection plus(Iterable right)
>
> Create a Collection as a union of two iterables. If the left iterable is a Set, then the returned collection will be a Set otherwise a List. This operation will always create a new object for the result, while the operands remain unchanged.

Because the "left" iterable is not a Set (it's a FileCollection), you get a List back, and Groovy just happens to use an ArrayList in the implementation.

huangapple
  • 本文由 发表于 2020年8月21日 15:06:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63518070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定