How could an idiomatic design of Serializable/Cloneable/… look like in Scala?

后端 未结 3 1468
情歌与酒
情歌与酒 2021-02-08 08:55

I wonder how much different these funcionality would look like (and how different the implementation would be), if Scala wouldn\'t (have to) follow Java\'s java.io.Seriali

相关标签:
3条回答
  • 2021-02-08 09:07

    Or are marker interfaces still the right choice in Scala?

    Nope. They aren't even the right choice in Java. They should be annotations, not interfaces.

    0 讨论(0)
  • 2021-02-08 09:17

    Serialization and cloning are both kind of special because of mutability:

    • Serialization, because it has to deal with cycles in the object graph, and;
    • Cloning because... Well, the only reason to clone an object is to prevent the accidental spread of mutable state.

    So, if you're willing to commit to a completely immutable domain model, you don't have object graphs as such anymore, you have object trees instead.

    For a functionally-oriented approach to serialization, SBinary is what I'd probably try first. For cloning, Just Don't Do It. :)

    0 讨论(0)
  • 2021-02-08 09:30

    the best way to do this in ideomatic scala is to use implicits with the effect of a typeclass. This is used for the Ordered trait

    def max[A <% Ordered[A]](a:A,b:A); 
    

    means the same as:

    def max[A](a:A,b:A)(implicit orderer: T => Ordered[A]);
    

    It says you can use every type A as long as it can be threated as an Ordered[A]. this has several benefits you don´t have with the interface/inheritance approach of Java

    1. You can add an implicit Ordered definition to an existing Type. You can´t do that with inheritance.

    2. You can have several implementation of Ordered for one Type! This is even more flexible than Type classes in Haskell wich allow only one instance per type.

    In conclusion scalas implicits used together with generics enable a very flexible approach to define Constraints on types.

    It is the same with cloneable/serializable.

    You may also want to look at the scalaz library which adds haskell like typeclasses to Scala such as Functor, Applicative and Monad and offers a rich set of implicits so that this concepts can also enrich the standart library.

    0 讨论(0)
提交回复
热议问题