1

I have an ArrayList<String>. I want to add n copies of a new String to it.

I've Googled generally and searched on StackOverflow. I've looked at the documentation.

Surely there's a better way than doing a loop?

I was hoping for something like:

myArray.addAll (ArrayList<String>(count: 10, value: "123"))
1
  • The reason I didn't put the myArray line as code, is because it's not actual code that someone could copy/paste into their kotlin project. But, whatever. Commented Jun 3, 2020 at 13:25

1 Answer 1

5

You can initialize a List with a given size n and an initializer function like this:

fun main() {
    val n = 10
    val defaultList = List(n) { it -> "default" }  // you can leave "it ->" here
    println(defaultList)
}

This piece of code then outputs

[default, default, default, default, default, default, default, default, default, default]

If you want to intialize an Array<String> directly without using a List as intermediate, you can do

val defaultArray: Array<String> = Array(n) { "default" }
println(defaultArray.contentToString())

in the main and get the same output (even without the it ->, which, indeed, isn't necessary in this case).

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Thanks. I knew there'd be an answer. I still haven't mastered closures yet.
So, to complete my answer, I have myArray.addAll (List (count) { "value" }. The "it ->" is not necessary in this case.
@Zonker.in.Geneva Nice, glad it helped... And yes, the it -> isn't necessary... You can fill up an Array directly, see the last edit of my answer.

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.