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

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With