Kotlin type mismatch, generics

Viewed 179

I found a strange behavior in kotlin. Given this code :

interface Animal

class Owl : Animal

class Page<T>(var list: List<T>)


fun ok(): List<Animal> {
    val list = listOf(
            Owl()
    )

    return list
}

fun error(): Page<Animal>  {
    val list = listOf(
            Owl()
    )

    val page: Page<Owl> = Page(list)

    return page
}

Owl implements Animal. The first function compiles, but on the second one, I've got the error :

Type mismatch.
Required: Page<Animal>
Found: Page<Owl>

I don't understand why kotlin can't do the type inference and guess that a Page<Owl> is also a Page<Animal>.

Can someone give me tips on this, and possibly some workaround ?

1 Answers

In your example the error() function returns invariant Page<Animal>, so it must be a Page<Animal> object: not a Page<Owl> one. You should add out to the generic to get it covariant, so the fixed implementation is:

fun error(): Page<out Animal>  {
    val list = listOf(
        Owl()
    )

    val page: Page<Owl> = Page(list)

    return page
}
Related