Provide listOfNotNull method.

This commit is contained in:
Ilya Gorbunov
2015-07-20 18:27:58 +03:00
parent 46858ddabd
commit d831509cee
2 changed files with 18 additions and 0 deletions
@@ -85,6 +85,12 @@ public fun hashSetOf<T>(vararg values: T): HashSet<T> = values.toCollection(Hash
/** Returns a new [LinkedHashSet] with the given elements. */
public fun linkedSetOf<T>(vararg values: T): LinkedHashSet<T> = values.toCollection(LinkedHashSet(mapCapacity(values.size())))
/** Returns a new read-only list either of single given element, if it is not null, or empty list it the element is null. The returned list is serializable (JVM). */
public fun <T : Any> listOfNotNull(value: T?): List<T> = if (value != null) listOf(value) else emptyList()
/** Returns a new read-only list only of those given elements, that are not null. The returned list is serializable (JVM). */
public fun <T : Any> listOfNotNull(vararg values: T?): List<T> = values.filterNotNull()
/**
* Returns an [IntRange] of the valid indices for this collection.
*/
@@ -47,6 +47,18 @@ class CollectionTest {
}
}
test fun listOfNotNull() {
val l1: List<Int> = listOfNotNull(null)
assertTrue(l1.isEmpty())
val s: String? = "value"
val l2: List<String> = listOfNotNull(s)
assertEquals(s, l2.single())
val l3: List<String> = listOfNotNull("value1", null, "value2")
assertEquals(listOf("value1", "value2"), l3)
}
test fun filterIntoSet() {
val data = listOf("foo", "bar")
val foo = data.filterTo(hashSetOf<String>()) { it.startsWith("f") }