+ 我要发布
我发布的 我的标签 发现
浏览器扩展
斑点象@Edge

Kotlin 里 Map 的扩展函数 getValue()

Kotlin Map 上的扩展函数 getValue() 返回一个与给定键相对应的现有值,或者抛出一个异常,提示找不到该键。如果该映射是用 withDefault 生成的,这个函数将返回默认值,而不是抛异常。 fun main(args: Array<String>) { //sampleStart val map = mapOf("key" to 42) // 返回不可空 Int 值 42 val value: Int = map.getValue("key") val mapWithDefault = map.withDefault { k -> k.length } // 返回 4 val value2 = mapWithDefault.getValue("key2") // map.getValue("anotherKey") // <- 这将抛出 NoSuchElementExc eption //sampleEnd println("value is $value") println("value2 is $value2") }
我的笔记