Scala 的案例类和类有什么区别? [英] What is the difference between Scala's case class and class?

查看:20
本文介绍了Scala 的案例类和类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Google 中搜索以找到 case classclass 之间的区别.每个人都提到,当您要对类进行模式匹配时,请使用案例类.否则,请使用类并提及一些额外的好处,例如 equals 和哈希代码覆盖.但是这些是人们应该使用案例类而不是类的唯一原因吗?

我想 Scala 中的这个特性应该有一些非常重要的原因.有什么解释或者有什么资源可以了解更多关于 Scala 案例类的信息?

解决方案

Case 类可以被看作是简单且不可变的数据保存对象,它们应该完全依赖于它们的构造函数参数.

这个功能概念允许我们

  • 使用紧凑的初始化语法 (Node(1, Leaf(2), None)))
  • 使用模式匹配分解它们
  • 隐式定义了相等比较

案例类与继承相结合,用于模拟代数数据类型.>

如果一个对象在内部执行有状态计算或表现出其他类型的复杂行为,它应该是一个普通类.

I searched in Google to find the differences between a case class and a class. Everyone mentions that when you want to do pattern matching on the class, use case class. Otherwise use classes and also mentioning some extra perks like equals and hash code overriding. But are these the only reasons why one should use a case class instead of class?

I guess there should be some very important reason for this feature in Scala. What is the explanation or is there a resource to learn more about the Scala case classes from?

解决方案

Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.

This functional concept allows us to

  • use a compact initialization syntax (Node(1, Leaf(2), None)))
  • decompose them using pattern matching
  • have equality comparisons implicitly defined

In combination with inheritance, case classes are used to mimic algebraic datatypes.

If an object performs stateful computations on the inside or exhibits other kinds of complex behaviour, it should be an ordinary class.

这篇关于Scala 的案例类和类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆