Kotlin containsValue用法及代码示例

本文方法及代码示例基于Kotlin 2.1.20 Released

containsValue 所在包 kotlin.collections.containsValue,其相关用法介绍如下:

用法:

kotlin 复制代码
fun <K, V> Map<K, V>.containsValue(value: V): Boolean

如果映射将一个或多个键映射到指定的 value ,则返回 true

允许克服需要传递类型为 V 的值的 containsValue 的 type-safety 限制。

代码示例:

kotlin 复制代码
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
}

// 输出
map.containsValue(1) is true
map.containsValue(1 as Number) is true
map.containsValue(2 as Any) is true
map.containsValue("string" as Any) is false

相关方法

相关推荐
用户2018792831677 小时前
Android黑夜白天模式切换原理分析
android
芦半山7 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android
卡尔特斯8 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
ace望世界8 小时前
安卓的ViewModel
android
ace望世界8 小时前
kotlin的委托
android
CYRUS_STUDIO10 小时前
一文搞懂 Frida Stalker:对抗 OLLVM 的算法还原利器
android·逆向·llvm
zcychong10 小时前
ArrayMap、SparseArray和HashMap有什么区别?该如何选择?
android·面试
CYRUS_STUDIO11 小时前
Frida Stalker Trace 实战:指令级跟踪与寄存器变化监控全解析
android·逆向
ace望世界16 小时前
android的Parcelable
android
顾林海16 小时前
Android编译插桩之AspectJ:让代码像特工一样悄悄干活
android·面试·性能优化