我在谷歌中搜索了case类和class之间的区别。每个人都提到,当你想在类上做模式匹配时,用例类。否则使用类,并提到一些额外的好处,如等号和哈希代码重写。但是这些就是为什么应该使用case类而不是类的唯一原因吗?

我想在Scala中应该有一些非常重要的原因。有什么解释,或者有资源可以学习更多关于Scala案例类的知识吗?


当前回答

没有人提到case类也是Product的实例,因此继承了这些方法:

def productElement(n: Int): Any
def productArity: Int
def productIterator: Iterator[Any]

其中productArity返回类参数的个数,productElement(i)返回第i个参数,productIterator允许遍历它们。

其他回答

类:

scala> class Animal(name:String)
defined class Animal

scala> val an1 = new Animal("Padddington")
an1: Animal = Animal@748860cc

scala> an1.name
<console>:14: error: value name is not a member of Animal
       an1.name
           ^

但是如果我们使用相同的代码,但是用例类:

scala> case class Animal(name:String)
defined class Animal

scala> val an2 = new Animal("Paddington")
an2: Animal = Animal(Paddington)

scala> an2.name
res12: String = Paddington


scala> an2 == Animal("fred")
res14: Boolean = false

scala> an2 == Animal("Paddington")
res15: Boolean = true

Person类:

scala> case class Person(first:String,last:String,age:Int)
defined class Person

scala> val harry = new Person("Harry","Potter",30)
harry: Person = Person(Harry,Potter,30)

scala> harry
res16: Person = Person(Harry,Potter,30)
scala> harry.first = "Saily"
<console>:14: error: reassignment to val
       harry.first = "Saily"
                   ^
scala>val saily =  harry.copy(first="Saily")
res17: Person = Person(Saily,Potter,30)

scala> harry.copy(age = harry.age+1)
res18: Person = Person(Harry,Potter,31)

模式匹配:

scala> harry match {
     | case Person("Harry",_,age) => println(age)
     | case _ => println("no match")
     | }
30

scala> res17 match {
     | case Person("Harry",_,age) => println(age)
     | case _ => println("no match")
     | }
no match

对象:单例模式:

scala> case class Person(first :String,last:String,age:Int)
defined class Person

scala> object Fred extends Person("Fred","Jones",22)
defined object Fred

case类是可以与match/case语句一起使用的类。

def isIdentityFun(term: Term): Boolean = term match {
  case Fun(x, Var(y)) if x == y => true
  case _ => false
}

你可以看到case后面跟着一个Fun类的实例,它的第二个参数是Var。这是一个非常漂亮和强大的语法,但它不能用于任何类的实例,因此对case类有一些限制。如果遵守了这些限制,就可以自动定义hashcode和equals。

模糊的短语“通过模式匹配的递归分解机制”仅仅意味着“它适用于大小写”。(实际上,match后面的实例与case后面的实例进行比较(匹配),Scala必须将它们都分解,并且必须递归地分解它们的组成部分。)

案例类对什么有用?维基百科上关于代数数据类型的文章给出了两个很好的经典例子,列表和树。支持代数数据类型(包括知道如何比较它们)是任何现代函数式语言都必须具备的功能。

哪些案例类是无用的?有些对象有状态,像connection.setConnectTimeout(connectTimeout)这样的代码不是用于case类的。

现在你可以读到Scala指南:Case Classes

Scala中的case类构造也可以看作是删除一些样板文件的便利工具。

在构造一个case类时,Scala提供了以下内容。

它创建了一个类及其伴生对象 它的伴生对象实现了apply方法,您可以将其用作工厂方法。你不必使用new关键字,从而获得了语法上的优势。

因为类是不可变的,所以你得到了访问器,它只是类的变量(或属性),而没有突变器(因此没有改变变量的能力)。构造函数参数作为公共只读字段自动提供给您。比Java bean构造好用得多。

默认情况下还可以获得hashCode、equals和toString方法,equals方法从结构上比较对象。生成一个复制方法来克隆一个对象(其中一些字段具有提供给该方法的新值)。

正如前面提到的,最大的优点是可以在case类上进行模式匹配。这是因为您获得了unapply方法,该方法允许您分解case类以提取其字段。


实际上,在创建case类(或者case对象,如果你的类不带参数)时,你从Scala得到的是一个作为工厂和提取器的单例对象。

从技术上讲,类和case类之间没有区别——即使编译器在使用case类时确实优化了一些东西。然而,一个case类用于消除特定模式的锅炉板,该模式正在实现代数数据类型。

这种类型的一个非常简单的例子是树。例如,二叉树可以这样实现:

sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[A](value: A) extends Tree
case object EmptyLeaf extends Tree

使我们能够做到以下几点:

// DSL-like assignment:
val treeA = Node(EmptyLeaf, Leaf(5))
val treeB = Node(Node(Leaf(2), Leaf(3)), Leaf(5))

// On Scala 2.8, modification through cloning:
val treeC = treeA.copy(left = treeB.left)

// Pretty printing:
println("Tree A: "+treeA)
println("Tree B: "+treeB)
println("Tree C: "+treeC)

// Comparison:
println("Tree A == Tree B: %s" format (treeA == treeB).toString)
println("Tree B == Tree C: %s" format (treeB == treeC).toString)

// Pattern matching:
treeA match {
  case Node(EmptyLeaf, right) => println("Can be reduced to "+right)
  case Node(left, EmptyLeaf) => println("Can be reduced to "+left)
  case _ => println(treeA+" cannot be reduced")
}

// Pattern matches can be safely done, because the compiler warns about
// non-exaustive matches:
def checkTree(t: Tree) = t match {
  case Node(EmptyLeaf, Node(left, right)) =>
  // case Node(EmptyLeaf, Leaf(el)) =>
  case Node(Node(left, right), EmptyLeaf) =>
  case Node(Leaf(el), EmptyLeaf) =>
  case Node(Node(l1, r1), Node(l2, r2)) =>
  case Node(Leaf(e1), Leaf(e2)) =>
  case Node(Node(left, right), Leaf(el)) =>
  case Node(Leaf(el), Node(left, right)) =>
  // case Node(EmptyLeaf, EmptyLeaf) =>
  case Leaf(el) =>
  case EmptyLeaf =>
}

注意,树的构造和解构(通过模式匹配)使用相同的语法,这也正是它们的打印方式(减去空格)。

它们也可以与哈希映射或集合一起使用,因为它们有一个有效、稳定的hashCode。

Case类可以进行模式匹配 Case类自动定义hashcode和equals Case类自动为构造函数参数定义getter方法。

(除了最后一个,你已经提到了所有的)。

这些是与常规课程的唯一区别。