I’m getting when using mutableLIstOf<Any>: T...
# announcements
c
I’m getting when using mutableLIstOf<Any>: Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly. I thought I understood it but trying to provide this type is being quite hard. I don’t understand which syntax I should use. The case is
Copy code
private var filteredList = mutableListOf<Any>()

if(filteredList.contains(item.resourceType)

data class Item (
    val resourceType: ResourceType? = null
)
Now if I give it the ResourceType straight it works. But I would like to understand why not. PS: The way I’m going around this, for now, I’m surrounding the case with when(type) and giving the type class directly into it ex:
Copy code
if(filteredList.contains(ResourceType)
c
The compiler needs can’t check for
resourceType
if it’s just a list of
Any
objects, since
Any
doesn’t have that property. If your goal is to filter
filteredList
again to only include items of type
Item
, you could do something like this:
Copy code
val filteredItems = filteredList.filterIsInstance<Item>()
That will produce a new list (
filteredItems
) which the compiler knows only contains
Item
objects. Then you can reference your property. Alternatively, you could do something like this, although its a bit more verbose:
Copy code
filteredList.forEach { listItem ->
    if (listItem is Item) {
        // now the compiler knows listItem is an Item and you can reference its properties
    } else {
        // the compiler still thinks listItem is an Any object here
    }
}
🌟 1
1
c
Damn man, thanks for the knowledge
c
no problem