Is it possible to specialize generic functions (or class) in Scala? For example, I want to write a generic function that writes data into a ByteBuffer:
def writeData[T](buffer: ByteBuffer, data: T) = buffer.put(data)
But as the put method takes only a byte and put it into the buffer, I need to specialize it for Ints and Longs as follows:
def writeData[Int](buffer: ByteBuffer, data: Int) = buffer.putInt(data)
def writeData[Long](buffer: ByteBuffer, data: Long) = buffer.putLong(data)
and it won't compile. Of course, I could instead write 3 different functions writeByte, writeInt and writeLong respectively, but let's say there is another function for an array:
def writeArray[T](buffer: ByteBuffer, array: Array[T]) {
for (elem <- array) writeData(buffer, elem)
}
and this wouldn't work without the specialized writeData functions: I'll have to deploy another set of functions writeByteArray, writeIntArray, writeLongArray. Having to deal with the situation this way whenever I need to use type-dependent write functions is not cool. I did some research and one possible workaround is to test the type of the parameter:
def writeArray[T](buffer: ByteBuffer, array: Array[T]) {
if (array.isInstanceOf[Array[Byte]])
for (elem <- array) writeByte(buffer, elem)
else if (array.isInstanceOf[Array[Int]])
for (elem <- array) writeInt(buffer, elem)
...
}
This might work but it's less efficient because type-checking is done in runtime unlike the specialized function version.
So my question is, what is the most desirable and preferred way to solve this kind of problem in Scala or Java? I appreciate your help in advance!
specialized
tag, because it turns out that this means something specific in Scala and it is exactly what you need. – Medea@specialized
is relevant here—it's not going to help with picking which ofputInt
,putLong
, etc. is needed. – Blab