W3cubDocs

/Kotlin

containsValue

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <K, V> Map<K, V>.containsValue(value: V): Boolean

Returns true if the map maps one or more keys to the specified value.

Allows to overcome type-safety restriction of containsValue that requires to pass a value of type V.

import kotlin.test.*
import java.util.*

fun main(args: Array<String>) {
//sampleStart
val map: Map<String, Int> = mapOf("x" to 1, "y" to 2)

// member containsValue is used
println("map.containsValue(1) is ${map.containsValue(1)}") // true

// extension containsValue is used when the argument type is a supertype of the map value type
println("map.containsValue(1 as Number) is ${map.containsValue(1 as Number)}") // true
println("map.containsValue(2 as Any) is ${map.containsValue(2 as Any)}") // true

println("map.containsValue("string" as Any) is ${map.containsValue("string" as Any)}") // false

// map.containsValue("string") // cannot call extension when the argument type and the map value type are unrelated at all
//sampleEnd
}

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/contains-value.html