How to safely cast CouchbaseLite Array to List<String>

In my data class (or POJO), I have a list of Strings among other things. I used setArray() to put the list of Strings in a document like so:

. . .
mutableDict.setArray(KEY_LIST_OF_STRINGS, MutableArray(pojo.listOfStrings.toList()))
. . .

So now, when accessing this array, how do I safely cast it from Array<Any> to List<String>. When I do the recommendation of Android Studio, which is to simply cast it using as (I’m using Kotlin), it complains further that that cast is unchecked. What do I do?

Thank you.

Well…

It really is a good thing that Android Studio warns you! Not only is the cast unsafe, it won’t work. The Array<Any> isn’t a List<String>. Attempting such a cast would cause a runtime exception.

There is a method, Array.toList that will return a List<Any>. It cannot return a List<String> because there is no guarantee, whatsoever, that the contents of the Array<> are all Strings.

You will have, either, to use Array.getString to get strings from the array, or you will have to verify the type of each object that you get from the list returned by Array.toList, to guarantee that it is, indeed a string.

1 Like

After converting the Array to List<<*>, use the filterIsInstance<String>() method.

You can do that if it works for you. OTOH, the results from getString(n) will be quite different from the results for toList().get(n) instanceof String.