Scala case class extending Product with Serializable

后端 未结 3 2124
执笔经年
执笔经年 2020-12-13 01:23

I am learning scala and tried following form Scala Cookbook:

trait Animal
trait FurryAnimal extends Animal
case class Dog(name:String) extends Animal
case cl         


        
3条回答
  •  一整个雨季
    2020-12-13 02:04

    All case classes in Scala posses a few properties:

    1. They will automatically extend the Product trait and a default implementation will be provided for them, as they can be viewed as a Cartesian Product of N records.
    2. They will extend Serializable as they are serializable out of the box (as a design choice).
    3. They will have an implementation of hashCode and equals provided by the compiler, which aids with pattern matching
    4. They will provide apply and unapply methods, for composition and decomposition of the type.

    Case classes are also Scala's way of expressing an Algebraic Data Type, more specifically a Product Type. Tuples are also a product type, and as so they also extend the Product trait.

    When you use two case classes with a common trait, the scala's compiler will use it's type inference algorithm to attempt to find the least upper bound (LUB) for the T type of the Array. Since both case classes extend Product and Serializable through the compiler, and the trait does not, it will during the search and apply it to the final calculated type.

    If you want to avoid seeing that, you can have your trait explicitly extend those traits:

    sealed trait Animal extends Product with Serializable
    

    More on this topic can be found here

提交回复
热议问题