Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array of non-nullable strings as array of nullable strings

Tags:

kotlin

I have a function that takes in an Array<String?>:

fun doStuff(words: 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

Preferably I'd like to avoid making SOME_WORDS an arrayOf<String?>(...) if possible.

like image 210
Nate Jenson Avatar asked Aug 24 '17 16:08

Nate Jenson


People also ask

Can we add NULL in string array?

No, it's not possible without creating a new array. You can't resize an array. s is a range variable that represents each string that is already in the array.

What is array out string?

A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string can not be changed. The String Array works similarly to other data types of Array. In Array, only a fixed set of elements can be stored.


1 Answers

Use an out-projected Array<out String?>:

fun doStuff(words: Array<out String?>) { /* ... */ }

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.

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 ?).

type variance diagram

The picture is taken from: A Whirlwind Tour of the Kotlin Type Hierarchy)

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.

like image 123
hotkey Avatar answered Oct 26 '22 17:10

hotkey