3

I have an array of nulls that I initialize with Strings. Then I have to pass it to a function that requires Array<String> instead of Array<String?>. So how can I go around this issue?

val list_names = arrayOfNulls<String>(plant_list.size)
for(item in plant_list){ list_names.plus(item.name) }

val myListAdapter = MyListAdapter(activity!!,list_names,list_types,list_images) // list_names must be Array<String>

I also want to mention that changing it in the Adapter would only complicate things, so I would like to do it all from here.

1
  • "Array instead of Array" what it means? Commented Jan 9, 2020 at 13:06

3 Answers 3

2

If you are sure that no null-values will be in your nullable array, you can simply (unsafe) cast it and it will work, e.g.:

val myListAdapter = MyListAdapter(activity!!,list_names as Array<String>,list_types,list_images)

If you have null values in there it depends a bit. One approach is then to first filter out the null-values and pass the resulting array, e.g.:

list_names.filterNotNull().toTypedArray()
// or in case you have different types in there and want only want a single matching one:
list_names.filterIsInstance<String>().toTypedArray()

But if you can: try to omit holding that array of nullable type in the first place. Can't you just filter out null values and collect the non-nullable only? That would probably the easiest and nicest way to collect the names as Array<String>, e.g.:

val list_names = plant_list.mapNotNull { it.name }.toTypedArray()
Sign up to request clarification or add additional context in comments.

Comments

2

To answer your direct question you can get a new Array without nulls using this:

val nonNullListNames = list_names.filterNotNull().toTypedArray()

But there are other issues with your code. There's no reason to create the array of nulls and add items to it. Every time you call list_names.plus(item.name) in your loop, you are creating a new Array that still has the original set of null values plus your new item(s).

Instead you can directly create a list of non-null items from the collection you're getting items from, and convert it to an Array:

val nonNullNamesArray = plant_list.map { it.name }.toTypedArray()

If your plant names are nullable, use this:

val nonNullNamesArray = plant_list.mapNotNull { it.name }.toTypedArray()

Comments

1

You cannot have a arrayOfNulls and convert a Nullable to a NonNull object. What I recommend to you is:

val list_names = mutableListOf<String>()
plant_list.foreach {
    list_names.add(it.name)
}
val myListAdapter = MyListAdapter(activity, list_names, list_types, list_images) 

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.