SomeStranger314
SomeStranger314

Reputation: 387

Save a case class in Scala to a text file and recreate it without any modification to the case class

How do I save a case class in my source code?

Background:

I am supposed to write a test for a mapper I wrote. Yet, my mapper gets a case class handed which has a list of hundreds of objects of another case classes as one of its attributes.

My Approach:

I would add Serializable Decorator to it as I read it described here: https://alvinalexander.com/scala/how-to-use-serialization-in-scala-serializable-trait

My Problem:

I don't have access to the case classes source. It's in a different file that I have imported.

Second Approach:

I tried to use unapply on the class, I got a long option string (About 23000 characters).

Problem, I can't turn it back to a class, mostly because as a written down string, it doesn't have quotation marks around the strings.

Has anyone a better method? Because if nothing helps, I will need to have to write my own class that can serialize, take on a string and map it back to the original case class. But since I am fairly new to Scala, I hope that that would be going overboard and Scala has a simple prebuild solution for this.

EDIT: Oh yes, I can't just add more dependencies, because it is not my project. Therefore I am looking for a standard function. (I am right now working on the "myOwnCaseClass" approach. It looks like it might be less work than I have expected above. But we'll see.

Upvotes: 0

Views: 1865

Answers (1)

stefanobaghino
stefanobaghino

Reputation: 12804

If Java serialization format is acceptable, you can leverage it for your purpose (case classes are inherently Serializable). Here are a few lines as an example (just change the path and you'll be able to copy and paste it to a Scala shell to see it running):

import java.io._

case class Foo(id: Long, name: Option[String])

val path = ??? // Write your path here

val fooToWrite = Foo(2L, None)
val out = new ObjectOutputStream(new FileOutputStream(path))
out.writeObject(fooToWrite)
out.close()

val in = new ObjectInputStream(new FileInputStream(path))
val fooToRead = in.readObject()
in.close()      

assert(fooToWrite == fooToRead)

Upvotes: 1

Related Questions