gpt4 book ai didi

collections - 这些功能在Kotlin Collections标准库中是重复的,还是有细微的差异?

转载 作者:行者123 更新时间:2023-12-02 13:23:19 31 4
gpt4 key购买 nike

我想知道功能之间是否有任何区别

// Returns true if the collection is empty
fun <T> Collection<T>.isEmpty(): Boolean


// Returns true if the collection has no elements
fun <T> Iterable<T>.none(): Boolean

两者之间有细微的差别吗?例如,包含null的Collection可以被认为是空的,或者Collection / Iterable有所作为?例如在List上调用这两个函数会有什么不同?这两个是否与 call 不同
!list.any()

要么
list.size() == 0

我也想知道两个功能之间是否有区别
operator fun <T> Iterable<T>.plus(element: T): List<T>


fun <T> Iterable<T>.plusElement(element: T): List<T>

如果不是,那么所有重复的原因是什么?

最佳答案

1-并非每个Iterable都是一个Collection。如果查看none()的实现,您会看到在集合实例中使用它时实际上会调用Collection.isEmpty:

/**
* Returns `true` if the collection has no elements.
*/
public fun <T> Iterable<T>.none(): Boolean {
if (this is Collection) return isEmpty()
return !iterator().hasNext()
}

2-是 operator overloadingoperator fun <T> Iterable<T>.plus(element: T): List<T>+运算符添加到 Iterable中,因此您可以执行以下操作:
val iterable: Iterable<String> = ...
val newIterable = iterable + "newItem"

关于collections - 这些功能在Kotlin Collections标准库中是重复的,还是有细微的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50003365/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com