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

2 Answers 2

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.

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

1 Comment

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

Comments

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.