I know that there is Jerkson and scalaxb and even Java’s XStream that successfully able to serialize scala’s data. I know that they handle well Strings, Integers and even case classes pretty well. But if I have function as one of the fields?
e.g. if I have something like:
case class Foo(bar: (Int) => Boolean, baz: Int)
Can these fields been somehow serialized to JSON or XML (actually, I don’t care to which one, they should be human-readable, thats why I don’t want to use SBinary)?
EDIT
Why would I want to do that?
Right now I’m writing implementation of decision tree. I don’t want to reconstruct that trees every time from training data hence I need to serialize them and that part could be done with SBinary. But additionally, it would be nice if as a humans we could look at serialized tree and analyze it.
It is not so wide task as I wrote in title, yes.
What I thinking now, is to write a custom serializer (e.g. for Jerkson) with my own format, or write to string field and then parse this back.
But I though that there could be some insanely better way to perform that.
No, a function is not necessary serializable… and serializable functions are unlikely to provide a human readable serialization.
If you want to be able to provide any kind of function, Im’ afraid there won’t be any solution. A possible workaround, if it can be used in your scenario, is to build a case class that implements
Function[Int, Boolean]and thus to go back to a case class scenario.For example, suppose that you have isolated that all your functions check whether a integer is exactly divisible by a given integer:
It’s clearly ultra-restrictive. But I’m afraid it’s the best you can achieve.
According to your edit. A solution might be to have a kind of factory class:
But here, you will lose type safety.