将不可为空的字符串数组作为可为空的字符串数组传递 [英] Pass array of non-nullable strings as array of nullable strings
问题描述
我有一个接受Array<String?>
的函数:
fun doStuff(words: Array<String?>) {
// ...
}
是否可以将Array<String>
传递给此函数?编译器照常给我一个类型不匹配"错误.
Is there a way I can pass in a Array<String>
to this function? As-is the compiler is giving me a "type mismatch" error.
private val SOME_WORDS = arrayOf("I", "want", "to", "use", "these")
doStuff(SOME_WORDS) // throws a type-mismatch error
最好尽量避免将SOME_WORDS
设置为arrayOf<String?>(...)
.
Preferably I'd like to avoid making SOME_WORDS
an arrayOf<String?>(...)
if possible.
推荐答案
使用 out
-投射 Array<out String?>
:
fun doStuff(words: Array<out String?>) { /* ... */ }
Kotlin中的数组是不变的,这意味着<对于任何不同的A
和B
(包括String
和String?
),c6>和Array<B>
都不是彼此的子类型,并且不能将它们分配并作为参数代替彼此传递.
Arrays in Kotlin are invariant, meaning that Array<A>
and Array<B>
are not subtypes of each other for any different A
and B
, including String
and String?
, and they cannot be assigned and passed as arguments in place of each other.
使用out
-投影Array<out String?>
使函数不仅接受Array<String?>
,而且接受具有String?
子类型的数组.基本上,由于类型是final
,所以只有一个这样的子类型,它是String
(非空类型,没有?
).
Using an out
-projection Array<out String?>
makes the function accept not only Array<String?>
but also arrays with subtypes of String?
. Basically, since the type is final
, there's only one such subtype, and it is String
(the non-null one, without ?
).
图片摄于:科特林式等级制度的旋风之旅 )
因此,该函数也将接受Arrray<String>
.但是您将无法将可为空的值放入数组中(这就是投影的工作方式),因此将保留类型安全性(和null-safety).
So, the function will accept Arrray<String>
as well. But you won't be able to put nullable values into the array (that's how the projection works), so the type safety (and null-safety) are preserved.
这篇关于将不可为空的字符串数组作为可为空的字符串数组传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!