Skip to content

Commit

Permalink
Samples of Map functions "contains" and "isNotEmpty"
Browse files Browse the repository at this point in the history
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
  • Loading branch information
mcserra and ilya-g committed Mar 31, 2020
1 parent 606b4db commit 61ad32f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
30 changes: 30 additions & 0 deletions libraries/stdlib/samples/test/samples/collections/maps.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Int> = 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, Int>): String =
when {
statisticsMap.isNotEmpty() -> {
val total = statisticsMap.values.sum()
"Total: [$total]"
}
else -> "<No values>"
}

val emptyStats: Map<String, Int> = mapOf()
assertPrints(totalValue(emptyStats), "<No values>")

val stats: Map<String, Int> = mapOf("Store #1" to 1247, "Store #2" to 540)
assertPrints(totalValue(stats), "Total: [1787]")
}

}

class Filtering {
Expand Down
7 changes: 6 additions & 1 deletion libraries/stdlib/src/kotlin/collections/Maps.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <K, V> Map<out K, V>.isNotEmpty(): Boolean = !isEmpty()

Expand Down Expand Up @@ -221,6 +224,8 @@ public inline fun <M, R> 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<out K, V>.contains(key: K): Boolean = containsKey(key)
Expand Down

0 comments on commit 61ad32f

Please sign in to comment.