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

后端 未结 3 1471
情歌与酒
情歌与酒 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题