Hasan Ghamloush
Hasan Ghamloush

Reputation: 21

I want to convert from Array<String?> to Array<String>?

I have this String array:

var parsedWeatherData: Array<String>?

And I want to add some weather data from JSON file using this code:

val weatherArray = forecastJson.getJSONArray(OWM_LIST)
parsedWeatherData = arrayOfNulls<String>(weatherArray.length())

The error is that the parsedWeatherData requires Array<String>? and not Array<String?>. How can I change the value from arrayOfNulls() to be of type Array<String>??

Upvotes: 2

Views: 84

Answers (3)

Francesco Re
Francesco Re

Reputation: 836

The function arrayOfNulls() returns an array of objects of String type with the given size, initialized with null values.
So parsedWeatherData is obviously an Array<String?> because values are null.

If you need Array<String> or Array<String>? you need to make sure that all the strings contained in the array are NOT null.

If think you should do something like this:

val weatherList = mutableListOf<String>()
for (i in 0 until weatherArray.length()) {    
    weatherList.add(weatherArray.getString(i))
}
parsedWeatherData = weatherList.toTypedArray()

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93571

To create an Array with non-nullables, you need to use the constructor with a lambda that initializes each element in the array, like this:

val weatherArray = forecastJson.getJSONArray(OWM_LIST)
parsedWeatherData = Array(weatherArray.length()) { index ->
    weatherArray[index]
}

And a couple suggestions... Lists are a little easier to work with, and you can make it non-nullable and just allow it to be empty when it doesn't have data. Then you don't have to handle null cases. So I'd do it like this:

// The property:
var parsedWeatherData: List<String> = emptyList()

// Parsing data:
val weatherArray = forecastJson.getJSONArray(OWM_LIST)
parsedWeatherData = List(weatherArray.length()) { index ->
    weatherArray[index]
}

Upvotes: 0

sangeetds
sangeetds

Reputation: 450

Array<String>? basically means this will be either a null value or an Array Of String.

Array<String?> means the array will contain null or String values.

You will be better changing the type of parsedWeatherData to Array<String?> if you are sure you will not assign it a null value later on. If you want it to remain as Array<String>? then you can use

parsedWeatherData = weatherArray.map { it }.toTypedArray()

Upvotes: 1

Related Questions