Josef Zoller
Josef Zoller

Reputation: 951

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?

Upvotes: 2

Views: 2506

Answers (3)

kr3v
kr3v

Reputation: 152

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).

Upvotes: 2

forpas
forpas

Reputation: 164204

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.

Upvotes: 3

Roman
Roman

Reputation: 2743

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

    val list2: ArrayList<String>

@Josef Zoller

Upvotes: -1

Related Questions