How to create a list with the same element n-times?

How to create a list with the same element n-times ?

Manually implementnation:

scala> def times(n: Int, s: String) =
 | (for(i <- 1 to n) yield s).toList
times: (n: Int, s: String)List[String]

scala> times(3, "foo")
res4: List[String] = List(foo, foo, foo)

Is there also a built-in way to do the same ?


See scala.collection.generic.SeqFactory.fill(n:Int)(elem: =>A) that collection data structures, like Seq, Stream, Iterator and so on, extend:

scala> List.fill(3)("foo")
res1: List[String] = List(foo, foo, foo)

WARNING It's not available in Scala 2.7.


Using tabulate like this,

List.tabulate(3)(_ => "foo")

(1 to n).map( _ => "foo" )

Works like a charm.


I have another answer which emulates flatMap I think (found out that this solution returns Unit when applying duplicateN)

 implicit class ListGeneric[A](l: List[A]) {
  def nDuplicate(x: Int): List[A] = {
    def duplicateN(x: Int, tail: List[A]): List[A] = {
      l match {
       case Nil => Nil
       case n :: xs => concatN(x, n) ::: duplicateN(x, xs)
    }
    def concatN(times: Int, elem: A): List[A] = List.fill(times)(elem)
  }
  duplicateN(x, l)
}

}

def times(n: Int, ls: List[String]) = ls.flatMap{ List.fill(n)(_) }

but this is rather for a predetermined List and you want to duplicate n times each element