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

相关方法

相关推荐
用户69371750013841 小时前
Google 推 AppFunctions:手机上的 AI 终于能自己干活了
android·前端·人工智能
用户69371750013842 小时前
AI让编码变简单,真正拉开差距的是UI设计和产品思考
android·前端·人工智能
zh_xuan2 小时前
Android Jetpack DataStore存储数据
android·android jetpack·datastore
程序员陆业聪2 小时前
在 Android 上跑大模型,你选错引擎了吗?
android
studyForMokey3 小时前
【Android面试】View绘制流程专题
android·面试·职场和发展
jjinl5 小时前
Android 资源说明
android
恋猫de小郭7 小时前
Swift 6.3 正式发布支持 Android ,它能在跨平台发挥什么优势?
android·前端·flutter
一只会跑会跳会发疯的猴子7 小时前
php操作ssl,亲测可用
android·php·ssl
程序员码歌8 小时前
火爆了,一个Skill搞定AI热点自动化:RSS 聚合 + AI 筛选 + 公众号 + 邮件全流程
android·前端·ai编程
优选资源分享8 小时前
小白转文字 v1.2.8.0 | 安卓离线免费音视频转写工具
android·音视频