0

I have a case class Person(name:String, id:Int) for serialization reasons (MessagePack), I need to convert this to a class. Is there an easy / elegant way to do this which does not require too much boilerplate or creation?

case class Person(name:String, id:Int) -> class Person(name:String, id:Int)

senia
  • 37,745
  • 4
  • 88
  • 129
user3335040
  • 649
  • 1
  • 7
  • 17
  • 12
    I don't understand.Case class is a class just with some extra methods which I think has no conflict with MessagePack. – Windor C Dec 23 '14 at 07:33
  • There's quite a lot to it if you want the exact same functionality: implementing and maintaining `Person.apply`, `copy`, `equals`, `hashCode`, `toString` and deriving from `Product`. –  Dec 23 '14 at 13:18

1 Answers1

1

A case class can be serialized as a "normal" class as it is de facto a normal class. As it makes all constructor arguments accessable by default it's an even better fit for serialisation than a normal class.

The case class just tells the compiler to automatically add some methods as equals and hashCode to the class. At the same time there is a companion object with an apply method added, but this doesn't affect the normal class at all.

So if there arise problems with Serialization the chance is quite hight that the source of the problem lies elsewhere.

You could try json4s https://github.com/json4s/json4s to convert your case class to JSON and then convert it to the MessagePack format.

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[Person])
val jsonString : String = write(Person("Andi", 42))

// convert with MessagePack as you would do with normal JSON
Andreas Neumann
  • 10,734
  • 1
  • 32
  • 52