简体   繁体   中英

Is possible to make a 3rd party class java.io.Serializable using Typeclasses in Scala ?

I want to implement java.io.Serializable for org.joda.time.format.DateTimeFormat in Scala. Is it possible to achieve this with Typeclasses

I don`t think it is possible because:

In order to serialize an object you need to know the whole state of the object so you can reconstruct the state in deserialization. How do you want to get the extremely complex state of DateTimeFormat -object? There is no public API available for that purpose.

And my advise: Don`t serialize the format object, it is sufficient to store it in static constants because it is immutable. This fully covers the use-case where both sides - provider and consumer - use the same format. If you really need to dynamically send format objects you can just send the format pattern strings (in most cases they are powerful enough) and use them in deserialization to construct format objects on the receiver.

java.io.Serializable 's design isn't suited for that. There are alternatives such as https://github.com/scala/pickling . However, they might not be applicable for DateTimeFormat , as Meno Hochshild mentions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM