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

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

问题描述

我在Google搜索了一个个案类和一个之间的区别。大家都提到,当你想对类进行模式匹配时,用例类就是这样。否则,使用类,并提到一些额外的额外津贴,如等于和哈希代码覆盖。但是,这些是为什么要使用案例类而不是类的唯一原因?

我想在Scala中这个功能应该有一些非常重要的原因。什么是解释或是否有资源来了解有关Scala案例类的更多信息?

解决方案

案例类可以看作是纯粹的和不可变的持有数据的对象应该完全依赖于它们的构造函数参数。



这个函数式概念允许我们




  • 使用紧凑的初始化语法( Node(1,Leaf(2),None)) li>
  • 使用模式匹配对它们进行分解

  • 具有隐式定义的相等性比较

  • b

    结合继承,case类用于模仿代数数据类型。 p>

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


    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 initialisation 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.

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

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