Home > Back-end >  Scala inner case class not serializable
Scala inner case class not serializable

Time:01-03

I am trying to do a very basic serialization of a very simple case class in Scala:

import org.scalatest.wordspec.AnyWordSpecLike
import java.io.{ByteArrayOutputStream, ObjectOutputStream}

class PersistenceSpec extends AnyWordSpecLike{
  case class TestClass(name: String) extends Serializable

  def serializeSomething(): ByteArrayOutputStream = {
    val testItem = TestClass("My Thing")
    val bos: ByteArrayOutputStream = new ByteArrayOutputStream()
    val oos = new ObjectOutputStream(bos)
    oos.writeObject(testItem)
    bos
  }

  "serializeSomething" when {
    "executed" must {
      "successfully serialize" in {
        val outputStream = serializeSomething()
        println(outputStream.toString())
      }
    }
  }
}

When I run this test I get a java.io.NotSerializableException on the call to oos.writeObject(testItem), which makes no sense, since case classes automatically implement Serializable, and this is the simplest possible example.

However, if I paste the code for TestClass and serializeSomething() into repl, I am able to call the function, and it works just fine.

What is different when calling my function via scalatest, vs repl that would cause this exception?

One final note: If I change the call from oos.writeObject(testItem) to oos.writeObject("Hello"), it works fine, even when run from scalatest.

CodePudding user response:

You need to define TestClass outside of PersistenceSpec. Inner class instances automatically get a reference to the instance of the outer class. So, when you write it out, it tries to serialize the PersistenceSpec instance as well, and that of course fails.

  • Related