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

相关方法

相关推荐
阿懂在掘金3 小时前
defineModel 是进步还是边界陷阱?双数据源组件的选择逻辑
vue.js·源码阅读
FunnySaltyFish3 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
砖厂小工6 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心7 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心7 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker9 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴10 小时前
Android17 为什么重写 MessageQueue
android
冬奇Lab1 天前
OpenClaw 源码精读(2):Channel & Routing——一条消息如何找到它的 Agent?
人工智能·开源·源码阅读
桦说编程1 天前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
阿巴斯甜1 天前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android