Ectoras Ectoras - 1 year ago 174
Scala Question

Convert Any type in scala to Array[Byte] and back

I have the following question:

I have a variable value in my program which is declared as Any value.

I want to convert this value to Byte Array..

How can I serialize to byte Array and back? I found examples related to other types such as Double or Int, but not as Any.

Answer Source

This should do what you need. It's pretty similar to how one would do it in Java.

import{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}

object Serialization extends App {

  def serialise(value: Any): Array[Byte] = {
    val stream: ByteArrayOutputStream = new ByteArrayOutputStream()
    val oos = new ObjectOutputStream(stream)

  def deserialise(bytes: Array[Byte]): Any = {
    val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))
    val value = ois.readObject

  println(deserialise(serialise("My Test")))
  println(deserialise(serialise(Map(1 -> 2))))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download