2

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

Yuri Geinish
  • 16,744
  • 6
  • 38
  • 40
  • 1
    Similar question (although about `Map` instead of `List` but the same applies): http://stackoverflow.com/q/34255329/3255152 – mfulton26 Nov 11 '16 at 14:00

1 Answers1

3

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)

hotkey
  • 140,743
  • 39
  • 371
  • 326