I am new to Scala and functional programming so this question might have a very simple answer. However, I was not able to figure it out so here it is:
I have a case-class hierarchy that represents an abstract syntax tree in a compiler. At some point I have a list of statements of the form List[Statement]
. This will get serialized with a Json array of objects where each object represents a statement. However, some kinds of statements are redundant so I don't want to serialize them. For example, returning void. The following code hopefully clarifies this:
sealed trait Statement
sealed trait Expression
case object Empty extends Expression
case class Return(e: Expression) extends Statement
What I want is to not serialize Return(Empty) at all. Right now I get something like:
"Return": {}
How can I simply ignore Return(Empty)
?
To make it more general. I don't want to have empty objects in my json like {}
. How can I make sure they don't make it to my json ?
Here is what I tried so far (and didn't work):
implicit val statementListWrites = StatementListWrites
object StatementListWrites extends Writes[List[Statement]] {
override def writes(stms: List[Statement]) =
JsArray(stms.filter(stm => {
stm match {
case Return(Empty) => false
case _ => true
}
}).map(s => Json.toJson(s)))
}
Perhaps the above technique works but for some reason it is not even called to begin with as far as I understand.