From 61ad32f012789ef95376ba30812c32e779c4806b Mon Sep 17 00:00:00 2001 From: Miguel Serra Date: Thu, 26 Dec 2019 14:39:19 +0000 Subject: [PATCH] Samples of Map functions "contains" and "isNotEmpty" Co-authored-by: Ilya Gorbunov --- .../samples/test/samples/collections/maps.kt | 30 +++++++++++++++++++ .../stdlib/src/kotlin/collections/Maps.kt | 7 ++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/libraries/stdlib/samples/test/samples/collections/maps.kt b/libraries/stdlib/samples/test/samples/collections/maps.kt index 9e1408eec9d..9e33ac6d31d 100644 --- a/libraries/stdlib/samples/test/samples/collections/maps.kt +++ b/libraries/stdlib/samples/test/samples/collections/maps.kt @@ -169,6 +169,36 @@ class Maps { // map.containsValue("string") // cannot call extension when the argument type and the map value type are unrelated at all } + + @Sample + fun containsKey() { + val map: Map = mapOf("x" to 1) + + assertTrue(map.contains("x")) + assertTrue("x" in map) + + assertFalse(map.contains("y")) + assertFalse("y" in map) + } + + @Sample + fun mapIsNotEmpty() { + fun totalValue(statisticsMap: Map): String = + when { + statisticsMap.isNotEmpty() -> { + val total = statisticsMap.values.sum() + "Total: [$total]" + } + else -> "" + } + + val emptyStats: Map = mapOf() + assertPrints(totalValue(emptyStats), "") + + val stats: Map = mapOf("Store #1" to 1247, "Store #2" to 540) + assertPrints(totalValue(stats), "Total: [1787]") + } + } class Filtering { diff --git a/libraries/stdlib/src/kotlin/collections/Maps.kt b/libraries/stdlib/src/kotlin/collections/Maps.kt index b06abb183bd..360629ef21f 100644 --- a/libraries/stdlib/src/kotlin/collections/Maps.kt +++ b/libraries/stdlib/src/kotlin/collections/Maps.kt @@ -180,7 +180,10 @@ internal expect fun mapCapacity(expectedSize: Int): Int @PublishedApi internal expect fun checkBuilderCapacity(capacity: Int) -/** Returns `true` if this map is not empty. */ +/** + * Returns `true` if this map is not empty. + * @sample samples.collections.Maps.Usage.mapIsNotEmpty + */ @kotlin.internal.InlineOnly public inline fun Map.isNotEmpty(): Boolean = !isEmpty() @@ -221,6 +224,8 @@ public inline fun M.ifEmpty(defaultValue: () -> R): R where M : Map<*, *> * Checks if the map contains the given key. * * This method allows to use the `x in map` syntax for checking whether an object is contained in the map. + * + * @sample samples.collections.Maps.Usage.containsKey */ @kotlin.internal.InlineOnly public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map.contains(key: K): Boolean = containsKey(key)