这些Kotlin Collections标准库中的函数是否重复,或者它们是否存在细微差别?

时间:2018-04-24 13:48:23

标签: collections kotlin

我想知道函数之间是否存在任何差异

// 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

这两者之间是否存在细微差别?例如,包含空值的Collection可以被视为空,或者Collection / Iterable是否有所不同?如何调用这两个函数(例如List)会有所不同?这两者中的任何一个都与调用

不同
!list.any()

list.size() == 0

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

operator fun <T> Iterable<T>.plus(element: T): List<T>

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

如果没有,那么所有两面性的原因是什么?

3 个答案:

答案 0 :(得分:1)

这是implementation of Iterable<T>.none()

public fun <T> Iterable<T>.none(): Boolean {
    if (this is Collection) return isEmpty()
    return !iterator().hasNext()
}

如您所知,如果实施是Collection<T>.isEmpty(),则会调用Collection

语义上的差异是none()可以尝试迭代容器以找出它没有元素(即它只使用iterator()),同时提供isEmpty()在具体的Collection子类型中使用自定义实现。

答案 1 :(得分:1)

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"

答案 2 :(得分:0)

无和任何

none()any()等函数主要与谓词函数一起使用,以测试任何元素是否与谓词匹配或 none 。< / p>

我认为没有方法是出于一致性的原因。

运营商关键字

operator关键字显示此函数实现了一个运算符。这里是+运算符,因此您可以使用加号来向任何迭代器添加元素并返回新的List,而您必须按名称使用方法plusElement将元素添加到iterable / list中

val listOfFour = listOf(1,2,3) + 4

https://kotlinlang.org/docs/reference/operator-overloading.html