Yuri Geinish
Yuri Geinish

Reputation: 17214

Kotlin generics mismatch in a class hierarchy

Why doesn't this work? It's working in Java though.

class MyList : java.util.LinkedList<String>()

fun main(args: Array<String>) {
    val x: java.util.List<String> = MyList()
}

I get

Type mismatch: inferred type is MyList but List<String> was expected

For the assignment line.

Link for online eval: http://try.kotlinlang.org/#/UserProjects/70dhmnocn8ueh73hg0o61mp01f/8ormftvrpbimfu0l3uf37galv

Upvotes: 2

Views: 268

Answers (1)

hotkey
hotkey

Reputation: 147981

Change your val declaration to:

val x: List<String> = MyList() // List<String>, not java.util.List<String>

What's likely the reason of this behavior is that Kotlin doesn't use the java.util.List<E> interface directly, instead, it is mapped to kotlin.collections.List<E> and kotlin.collections.MutableList<E>, which are imported by default, and there's even an IDE warning about java.util.List<T> usage.

Seemingly, java.util.List<E> is completely replaced with kotlin.collections.List<E> in the class hierarchy for LinkedList<String> during the type checking.

See the docs on Java collection interfaces mapping: (link)

Upvotes: 3

Related Questions