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

相关方法

相关推荐
浅影歌年43 分钟前
Android和h5页面相互传参
android
用户69371750013841 小时前
Kotlin 全量关键字全面整理,并附上简洁示例,确保每一个关键字都清楚易懂。
kotlin
用户69371750013841 小时前
搞懂 Kotlin 软关键字与硬关键字:灵活命名与语法陷阱全解析
android
下位子2 小时前
『OpenGL学习滤镜相机』- Day2: 渲染第一个三角形
android·opengl
风语者日志2 小时前
[LitCTF 2023]这是什么?SQL !注一下 !
android·数据库·sql
2501_915921433 小时前
iOS 26 CPU 使用率监控策略 多工具协同构建性能探索体系
android·ios·小程序·https·uni-app·iphone·webview
狂团商城小师妹3 小时前
JAVA国际版同城打车源码同城服务线下结账系统源码适配PAD支持Android+IOS+H5
android·java·ios·小程序·交友
游戏开发爱好者83 小时前
iOS 应用逆向对抗手段,多工具组合实战(iOS 逆向防护/IPA 混淆/无源码加固/Ipa Guard CLI 实操)
android·ios·小程序·https·uni-app·iphone·webview
虚伪的空想家4 小时前
ip网段扫描机器shell脚本
android·linux·网络协议·tcp/ip·shell·脚本·network
generallizhong4 小时前
android TAB切换
android·gitee