2

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

1
  • filterNotNull maybe will work for you? Commented Sep 9, 2020 at 14:54

3 Answers 3

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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]
}

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.