Kotlin (Mutable)List

时间:2019-01-18 18:39:02

标签: kotlin kotlin-interop

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?

3 个答案:

答案 0 :(得分:3)

There is no type (Mutable)List in Kotlin.

This serves as an indication that the type of list returned by Example.getList() will not be decided at compile time but it will be decided at run time.
In your case it will be List and not MutableList because Arrays.asList() returns a FixedSizeList.

If you implemented Example.getList() like this:

public static List<String> getList() {
    List<String> list = new ArrayList<>();
    list.add("A");
    list.add("B");
    list.add("C");
    return list;
}

then at runtime the type of your list would be MutableList.

答案 1 :(得分:2)

It's an IDEA tool tip which shows you that this list might be as MutableList, as List, as Example is Java class and it can return any of type list.

Also, the same happens to String: you don't know anything about 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. you can as invoke methods on it without null-check, as checking it on null: no warnings will appear).

答案 2 :(得分:-1)

MutableList is a interfece in kotlin. To declare a variable we need to use class like as

    val list2: ArrayList<String>

@Josef Zoller