Home Ask Login Register

Developers Planet

Your answer is one click away!

Peter February 2016

Using Generic Primitive Arrays in Scala

I recently asked this question about whether it was possible to parameterize the type of a primitive array in Java. (Basically, I have an array that I want to be either a double[] or a float[] based on some argument. I'm using arrays of primitives rather than arrays of wrapper classes (Double[], Float[]) because they're much more memory-and-time efficient, especially when dealing with big vector operations. The answer, it appears, is No, you can't do that in Java.

So, my new question is: Can I do this in Scala? I understand that primitives are kind of more hidden, and only boxed on certain operations... So if it is possible to parameterize my arrays as being of Double or Float, and the compiler does implement them as primitives, how do I tell if they're being unboxed, or otherwise implemented less efficiently than if I were to just go "Find: Double, Replace: Float" in my source code?


Clive Evans February 2016

Does this work for you?

object SpecialisedArray {
  def apply[@specialized(Float, Double) T: ClassTag](size: Int) = new Array[T](size)

Post Status

Asked in February 2016
Viewed 2,808 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life