I have one issue for a function that I wrote about the conversion of one Array[Byte] to a Array[T]. The function in question :
def getPoints[T](bytes : Array[Byte]) : Array[T] = {
val byteBuffer = ByteBuffer.wrap(bytes)
byteBuffer.order(ByteOrder.LITTLE_ENDIAN)
val data = Array.ofDim[T](bytes.length / biosRecord.byteEncoding)
if(biosRecord.byteEncoding == 2) {
byteBuffer.asShortBuffer.get(data)
data
} else if(biosRecord.byteEncoding == 4) {
byteBuffer.asIntBuffer().get(data)
data
} else null
}
biosRecord is a case class with a int field (byteEncoding).
I know there is two problems in this code :
- To return a generic array, I need to use
Manifest. - In the first
ifbranch, the inferred type isArray[Short]and in the second one isArray[Int]. This is why I tried to use a generic typeTbut it not works.
What I get at the compilation time :
[error] (x$1: Array[Short])java.nio.ShortBuffer <and>
[error] (x$1: Int)Short
[error] cannot be applied to (Array[T])
[error] byteBuffer.asShortBuffer.get(data)
[error] (x$1: Array[Int])java.nio.IntBuffer <and>
[error] (x$1: Int)Int
[error] cannot be applied to (Array[T])
[error] byteBuffer.asIntBuffer().get(data)
What do I need to do in order to make this generic function compiles ?
byteBuffer.asShortBuffer.get(data)get here takes an int or anArray[Short]but your array is generic, secondofDimneeds an implicitClassTagfor yourT.