Scala 案例类使用可序列化扩展产品

编程入门 行业动态 更新时间:2024-10-10 19:22:42
本文介绍了Scala 案例类使用可序列化扩展产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习 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 案例类使用可序列化扩展产品

本文发布于:2023-11-11 08:50:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577942.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:案例   序列化   产品   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!