2

I hope to construct MutableList a based List b, how can I do in Kotlin?

BTW, Code A is wrong

var a:MutableList<MSetting>
var b:List<MSetting>

Code A

var a=mutableListOf(b)

3 Answers 3

5

Kotlin has a few versions of the toMutableList() extension function that should cover you. Check out the documentation here.

Basically, on any Collection, Interable, typed Array or generic Array, you can call .toMutableList() and it will creat a new MutableList (backed by ArrayList).

So in your code, you can do this (I'm showing types, you can leave them off):

var b: List<MSetting> = listOf(...)
var a: MutableList<MSetting> = b.toMutableList()
Sign up to request clarification or add additional context in comments.

Comments

1

It is a generic and needs type information e.g.

    var a = mutableListOf<Int>()

I tested at https://try.kotlinlang.org/#/

EDIT: I didn't read closely enough, what you want should be a toMutableList method.

    var b = listOf(2, 3);
    var a = b.toMutableList()

Comments

1

it's very easy:

val listB = listA?.toMutableList() ?: mutableListOf() // list B = A if (A != null), other wise, B = new empty list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.