6

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)...

Jonas
  • 121,568
  • 97
  • 310
  • 388
teucer
  • 6,060
  • 2
  • 26
  • 36

2 Answers2

6

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.

Community
  • 1
  • 1
tenshi
  • 26,268
  • 8
  • 76
  • 90
  • I want to extend a class that needs arrays as input (to be more specific the DenseMatrix class from scalala). There the (@specialized) numeric types are implicitly converted to 'Scalar'. But you always need to give the whole array. I would like to have an approach close to 'R', i.e. when the array does not have the required length, just repeat and possibly cut it so that it fits... – teucer Jun 20 '11 at 14:43
5

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;
RoToRa
  • 37,635
  • 12
  • 69
  • 105