具有非null值的Kotlin地图 [英] Kotlin Map with non null values

查看:91
本文介绍了具有非null值的Kotlin地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Map,可以将扑克牌的字母转换为整数

Let say that I have a Map for translating a letter of a playing card to an integer

 val rank = mapOf("J" to 11, "Q" to 12, "K" to 13, "A" to 14)

使用地图时,即使地图和地图对是不可变的,我似乎也总是必须进行空安全检查:

When working with the map it seems that I always have to make a null safety check even though the Map and Pair are immutable:

val difference = rank["Q"]!! - rank["K"]!!

我想这是因为泛型类型具有任何作用?超型.为什么Map和Pair都是不可变的,为什么在编译时无法解决?

I guess this comes from that generic types have Any? supertype. Why can't this be resolved at compile time when both Map and Pair are immutable?

推荐答案

这与Map的实现无关(基于Kotlin或Java).您正在使用地图,并且地图可能没有键,因此[]运算符返回可为null的类型.

It is not about the implementation of Map (being it Kotlin or Java based). You are using a Map and a map may not have a key hence [] operator returns nullable type.

这篇关于具有非null值的Kotlin地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆