我正在学习 Scala 并尝试遵循 Scala Cookbook 的形式:
I am learning scala and tried following form Scala Cookbook:
trait Animal trait FurryAnimal extends Animal case class Dog(name:String) extends Animal case class Cat(name:String) extends Animal现在,当我执行以下操作时:
Now when I did following as :
val x = Array(Dog("Fido"),Cat("Felix"))结果显示为:
x:Array[Product with Serializable with Animal] = Array(Dog(Fido),Cat(Felix))虽然我知道案例类与产品特征混合在一起
我没有得到的是:带有动物序列化的产品
据我了解,产品与模式匹配有关
我用谷歌搜索了但没有得到任何东西.请帮助我详细了解这个概念.
I did google it but didn't get anything.Please Help to get me the concept in detail.
谢谢
推荐答案这是一个预期的行为,因为 case class 是如何工作的.case class 自动extends 两个traits,分别是Product 和Serializable.
This is an expected behavior because of how case class works. case class automatically extends two traits, namely Product and Serializable.
Product trait 被扩展为 case class 是一个 代数数据类型与产品类型.
Product trait is extended as case class is an algebraic data type with product type.
Serializable trait 得到扩展,以便 case class 可以被视为纯数据 - 即能够被序列化.
Serializable trait is extended so that case class can be treated as a pure data - i.e capable of being serialized.
与case class Dog 和Cat 不同,你的特征Animal 不继承Product 或 Serializable.因此,您看到的类型签名.
Unlike case class Dog and Cat, your trait Animal does not extend Product or Serializable. Hence the type signature you see.
当您声明类似 Array(Dog(""), Cat("")) 时,scalac 需要推断单个 top type 可以表示给定数组的所有元素.
When you declare something like Array(Dog(""), Cat("")), scalac needs to infer single top type that can represent all the elements of given array.
这就是为什么推断类型是 Product with Serializable with Animal 因为 Animal 没有扩展 Product 也没有 Serializable而 case 类 是隐式的.
That's why the inferred type is Product with Serializable with Animal as Animal did not extend Product nor Serializable while the case class did implicitly.
要解决此推断,您可以通过 Animal 使类型显式,或者使 Animal 扩展 Product 和 Serializable.
To work around this inference, you can either make type explicit by Animal or make Animal extend Product and Serializable.
trait Animal extends Product with Serializable case class Dog(name: String) extends Animal case class Cat(name: String) extends Animal Array(Dog(""), Cat("")) // Array[Animal] = Array(Dog(), Cat())更多推荐
Scala 案例类使用可序列化扩展产品
发布评论