1

I need to write a function in Scala that returns an Array of byte serializated with AvroOutputStream, but in scala i can't get the class of the generic object i'm passing in input. Here is my util class:

class AvroUtils {

    def createByteArray[T](obj: T): Array[Byte] = {
        val byteArrayStream = new ByteArrayOutputStream()
        val output = AvroOutputStream.binary[T](byteArrayStream)
        output.write(obj)
        output.close()
        byteArrayStream.toByteArray()
    }
}

As you can see if tou test this code is that AvroOutputStream can't recognize the T class so it can't generate a schema for it. Hope you can help! thanks

PS: Already tried with TypeTag and ClassTag, nothing works.

Pasq
  • 45
  • 8

1 Answers1

1

You need to add the proper implicits for T, namely SchemaFor and ToRecord:

def createByteArray[T : SchemaFor : ToRecord](obj: T): Array[Byte] = {
  val byteArrayStream = new ByteArrayOutputStream()
  val output = AvroOutputStream.binary[T](byteArrayStream)
  output.write(obj)
  output.close()
  byteArrayStream.toByteArray()
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • maybe ... def createByteArray[T : SchemaFor : ToRecord](obj: T): Array[Byte] ? – HoTicE Jul 27 '18 at 08:49
  • i have another problem if one of the field is AnyRef AvroInputStream.binary[T](byteArrayStream) failed to compile with : Could not find implicit SchemaFor – HoTicE Aug 01 '18 at 08:57