Search code examples
arrayskotlincomparecontains

kotlin "contains" doesn't work as expected


I am working with a method which filters the preferences which match with the ids, I am using the contains method, but even though the values are the same, the contains is showing a false in each iteration. The method looks like:

private fun filterPreferencesByIds(context: MyPodCastPresenterContext): List<FanPreferences> {
            return context.preferences?.filter {
                context.ids.contains(it.id)
            }
        }

The values of the arrays are:

for the context.ids: "B52594F5-80A4-4B18-B5E2-8F7B12E92958" and "3998EDE7-F84B-4F02-8E15-65F535080100"

enter image description here

And for the context.preferences:

enter image description here

But even though, when the first and the final ids have the same id value as the context.ids, the contains is false in the debug. I think it could be related with the types in the context.ids rows Json$JsonTextNode. Because when I did the same with numeric values hardcoded the compare is successful.

Any ideas?

Thanks!


Solution

  • If the type of FanPreferences.id is String and the type of context.ids list element is JsonTextNode, you won't find an element equal to the given id string, because it's not of String type.

    Try mapping your context ids to the list of strings before filtering:

    val ids = context.ids.map { it.toString() }.toSet()
    return context.preferences?.filter {
        ids.contains(it.id)
    }
    

    Note that calling toString() on JsonTextNode might be not the best way to get the string data from it. It's better to consult the API documentation of that class to find it out.