Kotlin Collection extension function .all {} produce true for empty collection. Solution !

/**
* Returns `true` if all elements match the given [predicate].
*
*
@sample samples.collections.Collections.Aggregates.all
*/
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
if (this is Collection && isEmpty()) return true
for (element in this) if (!predicate(element)) return false
return true
}
val list = listOf<String>("OK", "OK")
val isTrue : Boolean = list.all { it == "OK" }
val list = listOf<String>()
val isTrue : Boolean = list.all { it == "OK" }
val isTrue = if (list.isEmpty()) {
false
} else {
list.all { it == "OK" }
}
public inline fun <T> Iterable<T>.only(predicate: (T) -> Boolean): Boolean {
if (this is Collection && isEmpty()) return false
for (element in this) if (!predicate(element)) return false
return true
}
val list = listOf<String>()
val isTrue : Boolean = list.only { it == "OK" }
class GeneralExtensionsKtTest {

@Test
fun `only extension function should return false if not all elements match a definition`() {
val list = listOf("OK", "Not OK")
assertThat(list.only { it == "OK" }).isFalse()
}

@Test
fun `only extension function should return true if all elements match a definition`() {
val list = listOf("OK", "OK")
assertThat(list.only { it == "OK" }).isTrue()
}

@Test
fun `only extension function should return false if list is not empty but elements not match a definition`() {
val list = listOf("Not OK")
assertThat(list.only { it == "OK" }).isFalse()
}

@Test
fun `only extension function should return false if list is empty`() {
val list = listOf<String>()
assertThat(list.only { it == "OK" }).isFalse()
}

@Test
fun `standard Kotlin all extension function for empty list will return true`() {
val list = listOf<String>()
assertThat(list.all { it == "OK" }).isTrue()
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store