Search code examples
kotlingenericstypes

Kotlin: Adding generics to a List<Any>


I have a generic object:

data class MyObject<T>(
    val entity: T
)

I want to concatenate two lists of these objects, with different types T, and return them.

I tried

fun concatLists(): List<MyObject<Any>> {
val listOfAs = listOf(MyObject<A>())
val listOfBs = listOf(MyObject<B>())

return mutableListOf<MyObject<Any>>().also {
            it.addAll(listOfAs)
            it.addAll(listOfBs)
        }
}

however I get the error:

Type mismatch.
Required:
Collection<MyObject<Any>>
Found:
List<MyObject<A>>

I don't understand why this error is being thrown as I thought Collection was a child of List, and type A was a child of Any, that this would work.


Solution

  • For your use case you can use star projection, like

    fun concatLists(): List<MyObject<*>> {
        val listOfAs = listOf(MyObject(A()))
        val listOfBs = listOf(MyObject(B()))
    
        return mutableListOf<MyObject<*>>().also {
            it.addAll(listOfAs)
            it.addAll(listOfBs)
        }
    }
    

    See also Difference between "*" and "Any" in Kotlin generics