Add Collections.isNullOrEmpty #KT-23279

This commit is contained in:
Jeff Wright
2018-02-20 10:03:27 -06:00
committed by Ilya Gorbunov
parent 6a140fb9ed
commit 292f69936b
2 changed files with 26 additions and 0 deletions
@@ -51,6 +51,18 @@ class Collections {
assertPrints(collection.orEmpty(), "[a, b, c]")
}
@Sample
fun collectionIsNullOrEmpty() {
val nullCollection: Collection<Any>? = null
assertTrue(nullCollection.isNullOrEmpty())
val emptyCollection: Collection<Any>? = listOf()
assertTrue(emptyCollection.isNullOrEmpty())
val collection: Collection<Char>? = listOf('a', 'b', 'c')
assertFalse(collection.isNullOrEmpty())
}
@Sample
fun collectionContainsAll() {
val collection = mutableListOf('a', 'b')
@@ -10,6 +10,7 @@ package kotlin.collections
import kotlin.*
import kotlin.comparisons.compareValues
import kotlin.internal.contracts.*
internal object EmptyIterator : ListIterator<Nothing> {
override fun hasNext(): Boolean = false
@@ -168,6 +169,19 @@ public val <T> List<T>.lastIndex: Int
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.isNotEmpty(): Boolean = !isEmpty()
/**
* Returns `true` if the collection is null or if it is empty.
* @sample samples.collections.Collections.Collections.collectionIsNullOrEmpty
*/
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this@isNullOrEmpty != null)
}
return this == null || this.isEmpty()
}
/**
* Returns this Collection if it's not `null` and the empty list otherwise.
* @sample samples.collections.Collections.Collections.collectionOrEmpty