*just for learning purpose
In Kotlin we can create an array to hold multiple data types including null as bellow
var multiDataArray = arrayOf(10, "Book", 10.99, 'A', null)
But if we try to create an Array with Any type in either way bellow
val values: Array<Any> = arrayOfNulls(items.size)
val values: Array<Any> = Array<Any>(items.size){null}
it is not allowed compiler with the error of
'Kotlin: Type mismatch: inferred type is Array<Any?> but Array<Any> was expected'
it is suggesting to use val values: Array<Any?>
Question 1. What's the reason for that? it sounds like for null safety, indicating the compiler the possibility of null?
What if I want an array that I guarantee for no null values. do I still need to define it as Array<Any?> like bellow as below.
//This one will give the compile error
fun arrayTest0(items: Array<Any>): Array<Any> {
val values: Array<Any> = arrayOfNulls(items.size)
var i = 0;
items.forEach { num -> values[i++] = num }
return values;
}
//The working one
fun arrayTest1(items: Array<Any?>): Array<Any?> {
val values: Array<Any?> = arrayOfNulls(items.size)
var i = 0;
items.forEach { num -> values[i++] = num }
return values;
}
Anymeans nulls are disallowed.Any?allows null values. You really should read official docs: kotlinlang.org/docs/null-safety.html .