英文:
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:
英文:
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:
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论