Kotlin Collections标准库中的这些函数是重复的,还是有细微的差异?
我想知道这些函数之间是否有任何区别Kotlin Collections标准库中的这些函数是重复的,还是有细微的差异?,collections,kotlin,Collections,Kotlin,我想知道这些函数之间是否有任何区别 // Returns true if the collection is empty fun <T> Collection<T>.isEmpty(): Boolean operator fun <T> Iterable<T>.plus(element: T): List<T> 或 我还想知道这两个函数之间是否有任何区别 // Returns true if the collection is em
// Returns true if the collection is empty
fun <T> Collection<T>.isEmpty(): Boolean
operator fun <T> Iterable<T>.plus(element: T): List<T>
或
我还想知道这两个函数之间是否有任何区别
// Returns true if the collection is empty
fun <T> Collection<T>.isEmpty(): Boolean
operator fun <T> Iterable<T>.plus(element: T): List<T>
运算符fun Iterable.plus(元素:T):列表
及
funiterable.pluseElement(元素:T):列表
如果没有,那么所有口是心非的原因是什么?没有,也没有
像none()
或any()
这样的函数通常与谓词函数一起使用,以测试是否有元素分别与谓词匹配或不匹配
出于一致性的原因,我假设不使用的方法是存在的
运算符关键字
运算符关键字显示此函数实现运算符。这里是+
运算符,因此您可以使用加号将元素添加到任何迭代器并返回新列表,而您必须使用方法pluseElement
按名称将元素添加到iterable/List
val listOfFour = listOf(1,2,3) + 4
这里有一个:
public fun Iterable.none():布尔值{
如果(这是集合)返回isEmpty()
return!iterator().hasNext()
}
您可能注意到,如果实现是集合,它将调用集合.isEmpty()
语义上的区别在于,none()
可以尝试在容器上迭代以发现它没有元素(即,它只使用iterator()
),而isEmpty()
在具体的集合
子类型中提供了自定义实现。1-并非每个Iterable
都是集合
。如果查看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-我想我还是不明白有两个不同功能的原因。如果只让运算符重载一个,您仍然可以选择像val newIterable=iterable+“newItem”或val newIterable=iterable.plus(“newItem”)那样调用它,那么第二个函数pluseElement()的用途是什么?
val listOfFour = listOf(1,2,3) + 4
public fun <T> Iterable<T>.none(): Boolean {
if (this is Collection) return isEmpty()
return !iterator().hasNext()
}
/**
* Returns `true` if the collection has no elements.
*/
public fun <T> Iterable<T>.none(): Boolean {
if (this is Collection) return isEmpty()
return !iterator().hasNext()
}
val iterable: Iterable<String> = ...
val newIterable = iterable + "newItem"