如何告诉Kotlin数组或集合不能包含空值? [英] How can I tell Kotlin that an array or collection cannot contain nulls?

查看:437
本文介绍了如何告诉Kotlin数组或集合不能包含空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个数组,然后填充它,Kotlin认为该数组中可能存在null,并强迫我对此进行解释

If I create an array, then fill it, Kotlin believes that there may be nulls in the array, and forces me to account for this

val strings = arrayOfNulls<String>(10000)
strings.fill("hello")
val upper = strings.map { it!!.toUpperCase() } // requires it!!
val lower = upper.map { it.toLowerCase() } // doesn't require !!

创建填充数组不会出现此问题

Creating a filled array doesn't have this problem

val strings = Array(10000, {"string"})
val upper = strings.map { it.toUpperCase() } // doesn't require !!

如何告诉编译器strings.fill("hello")的结果是NonNull数组?

How can I tell the compiler that the result of strings.fill("hello") is an array of NonNull?

推荐答案

经验法则:如有疑问,请明确指定类型(对此有特殊的重构):

A rule of thumb: if in doubts, specify the types explicitly (there is a special refactoring for that):

val strings1: Array<String?> = arrayOfNulls<String>(10000)
val strings2: Array<String>  = Array(10000, {"string"})

因此您看到strings1包含可为空的项目,而strings2则不包含.那并且只有那决定了如何使用这些数组:

So you see that strings1 contains nullable items, while strings2 does not. That and only that determines how to work with these arrays:

// You can simply use nullability in you code:
strings2[0] = strings1[0]?.toUpperCase ?: "KOTLIN"

//Or you can ALWAYS cast the type, if you are confident:
val casted = strings1 as Array<String>

//But to be sure I'd transform the items of the array:
val asserted = strings1.map{it!!}
val defaults = strings1.map{it ?: "DEFAULT"}

这篇关于如何告诉Kotlin数组或集合不能包含空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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