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

相关方法

相关推荐
快乐觉主吖6 分钟前
Unity的日志管理类
android·unity·游戏引擎
明月看潮生14 分钟前
青少年编程与数学 01-011 系统软件简介 06 Android操作系统
android·青少年编程·操作系统·系统软件·编程与数学
snetlogon2017 分钟前
JDK17 Http Request 异步处理 源码刨析
android·网络协议·http
消失的旧时光-19431 小时前
Android USB 通信开发
android·java
吃汉堡吃到饱1 小时前
【Android】浅析View.post()
android
咕噜企业签名分发-淼淼1 小时前
开发源码搭建一码双端应用分发平台教程:逐步分析注意事项
android·ios
betazhou2 小时前
mariadb5.5.56在centos7.6环境安装
android·数据库·adb·mariadb·msyql
doublelixin8 小时前
AOSP (Android11) 集成Google GMS三件套
android
xzkyd outpaper11 小时前
onSaveInstanceState() 和 ViewModel 在数据保存能力差异
android·计算机八股
梓仁沐白12 小时前
【Kotlin】协程
开发语言·python·kotlin