scala 2.11.8 how to fill an array

3.2k Views Asked by At

I want to create an array that contains the same value repeated for a very large number of times, say 1,000,000.

I was thinking to use something like Array.fill(1000000)(0). However, after reading the documentation for Scala 2.11.8, I found that there is no such members of Array in this version.

Is there any other ways that can create the array without using loop? Thanks in advance for your help.

3

There are 3 best solutions below

0
On BEST ANSWER

You can use range to iterate through required length (1000000 times in your case) and then return a default value which is 0 in each iteration as below.

val arr:Array[Int] = (1 to 1000000 map(_ => 0)).toArray
0
On

Stream.continually(0).take(1000000).toArray would do that .. but why in the world would you want something like this???

0
On

This will do the trick:

Array.fill[Int](1000000)(0)

Read more here: https://alvinalexander.com/scala/scala-list-class-examples