There is such a code on Kotlin:

val collection: java.util.Collection<String> = java.util.ArrayList<String>()

why it is compiled with the error: type mismatch: inferred type is ArrayList<String> but Collection<String> was expected . This is probably normal behavior, but I can not understand why.

    1 answer 1

    In the Kotlin type hierarchy, the types java.util.Collection , java.util.List and other interfaces of the collections of the standard Java library are replaced with analogues from kotlin.collections.* Imported by default, for example List are the so-called mapped types .

    In addition, each collection interface from the standard Java library is mapped into two types - a read-only interface and a mutable collection interface:
    java.util.ListList (does not contain functions for changing the list) and MutableList .

    Because of this, when checking types, the Kotlin ArrayList compiler is not java.util.List or java.util.Collection (hence the error), instead its type hierarchy has kotlin.collections.List , kotlin.collections.Collection .

    IntelliJ IDEA warns that the collection interfaces from java.util.* Should not be used in Kotlin code.


    The easiest way to fix the error is to replace the interfaces from java.util.* kotlin.collections.* corresponding interfaces from kotlin.collections.* :

     val collection: Collection<String> = ArrayList<String>() 

    or accordingly

     val collection: MutableCollection<String> = ArrayList<String>() 

    See also a similar question on StackOverflow .