问题
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.Serializable
/java.lang.Cloneable
(mostly to stay compatible with Java and the tools/ecosystem around it).
Because Scala is more simpler in language design, but enables more powerful implementation and abstraction possibilities, it is thinkable that Scala might take a different path compared to Java, if it wouldn't have to shoulder the Java-compatibility-burden.
I could imagine that a idiomatic implementation would use type classes or traits with (possibly) private fields/methods (not possible in Java interfaces?), maybe carrying some standard implementation?
Or are marker interfaces still the right choice in Scala?
回答1:
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. :)
回答2:
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.
回答3:
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
You can add an implicit Ordered definition to an existing Type. You can´t do that with inheritance.
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.
来源:https://stackoverflow.com/questions/6317896/how-could-an-idiomatic-design-of-serializable-cloneable-look-like-in-scala