kotlinkotlin-interop

Kotlin (Mutable)List


If you access a Java value of type List<[Some Type]> in Kotlin, you will get the type (Mutable)List<[Some Type]!>!.

e.g.:

Java code:

public class Example {
    public static List<String> getList() {
        return Arrays.asList("A", "B", "C");
    }
}

Kotlin code:

val list = Example.getList()
// list is of type (Mutable)List<String!>!

Here is, how IntelliJ shows it:

IntelliJ type hint

However, if you want to make your own variable of this type like so:

val list2: (Mutable)List<String>

Then IntelliJ will correctly highlight the type but will give the error Unexpected Tokens.

What is this (Mutable)List?


Solution

  • It is an IntelliJ IDEA tooltip that shows that the type of this list can be either MutableList or List, as Example.getList() is defined in Java, which means it can return either type of the list.

    Also, the same happens to String: you don't know anything about the list's String nullability, as it is returned from Java, so String looks like String! meaning 'maybe it's null, but or maybe not' without affecting compilation (i.e. on such String! values you can both invoke methods without a null-check and actually make a null-check - no warnings will appear in neither case).