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

相关方法

相关推荐
消失的旧时光-19432 小时前
Kotlin 判空写法对比与最佳实践
android·java·kotlin
锅拌饭3 小时前
Android Handler(一) 同步屏障泄露导致页面假死
android
锅拌饭3 小时前
Android Handler(二) 同步屏障泄露检测
android
手机不死我是天子4 小时前
《Android 核心组件深度系列 · 第 3 篇 BroadcastReceiver》
android·android studio
用户17345666963474 小时前
Android 日志库:高性能压缩加密日志系统
android
恋猫de小郭5 小时前
React 和 React Native 不再直接归属 Meta,React 基金会成立
android·前端·ios
bst@微胖子5 小时前
鸿蒙实现滴滴出行项目之侧边抽屉栏以及权限以及搜索定位功能
android·华为·harmonyos
zcz16071278215 小时前
Docker Compose 搭建 LNMP 环境并部署 WordPress 论坛
android·adb·docker
Pika15 小时前
深入浅出 Compose 测量机制
android·android jetpack·composer