0
votes

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.

1
You might try writing it as json using something like json4s. - Don Branson
Oh yes, I forgot to mention. I can't just add dependencies. Standard Library only. It's kind of a project in my internship. I will update my question with this information. - SomeStranger314
Do you want to serialize some specific case class? Or do you need to handle a general case? In general case you can serialize not all classes. Imagine if your class has a field of type Thread. How can it be serialized? Using some standard serialization library such as JSON serialization with external configuration (json4s, circe, play-json) might be a good idea. Or you might roll out your custom serialization basing on ideas in those libraries. - SergGr
case classes are inherently Serializable (as long as its contents are). Would Java serialization format be acceptable? - stefanobaghino
@stefanobaghino for that I have to add the decorator, don't I? And therefore I face the same problem. - SomeStranger314

1 Answers

1
votes

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)