Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala repeat Array

Tags:

arrays

scala

I am a newbie to scala. I try to write a function that is "repeating" an Array (Scala 2.9.0):

def repeat[V](original: Array[V],times:Int):Array[V]= {
if (times==0)
   Array[V]()
else
  Array.concat(original,repeat(original,times-1)
}

But I am not able to compile this (get an error about the manifest)...

like image 494
teucer Avatar asked Jun 20 '11 13:06

teucer


2 Answers

You need to ask compiler to provide class manifest for V:

def repeat[V : Manifest](original: Array[V], times: Int): Array[V] = ...

The answer to question: why is that needed, you can find here:

Why is ClassManifest needed with Array but not List?

I'm not sure where you want to use it, but I can generally recommend you to use List or other suitable collection instead of Array.

like image 161
tenshi Avatar answered Nov 09 '22 16:11

tenshi


BTW, an alternative way to repeat a Array, would be to "fill" a Seq with references of the Array and then flatten that:

def repeat[V: Manifest](original: Array[V], times: Int) : Array[V] = 
  Seq.fill(times)(original).flatten.toArray;
like image 20
RoToRa Avatar answered Nov 09 '22 14:11

RoToRa