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

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


当前回答

类:

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类实例,相等性纯粹是根据对象字段的值定义的。

下面列出了case类的一些关键特性

Case类是不可变的。 可以实例化case类而不需要new关键字。 案例类可以根据值进行比较

scala fiddle的示例代码,摘自scala文档。

https://scalafiddle.io/sf/34XEQyE/0

除了人们已经说过的,类和案例类之间还有一些更基本的区别

1.Case Class不需要显式的new,而Class需要用new调用

val classInst = new MyClass(...)  // For classes
val classInst = MyClass(..)       // For case class

2.默认情况下,构造函数的形参在类中是私有的,而在case类中是公共的

// For class
class MyClass(x:Int) { }
val classInst = new MyClass(10)

classInst.x   // FAILURE : can't access

// For caseClass
case class MyClass(x:Int) { }
val classInst = MyClass(10)

classInst.x   // SUCCESS

3.Case类根据值进行比较

// For Class
class MyClass(x:Int) { }
 
val classInst = new MyClass(10)
val classInst2 = new MyClass(10)

classInst == classInst2 // FALSE

// For Case Class
case class MyClass(x:Int) { }
 
val classInst = MyClass(10)
val classInst2 = MyClass(10)

classInst == classInst2 // TRUE

与类不同,case类仅用于保存数据。

Case类对于以数据为中心的应用程序来说非常灵活,这意味着您可以在Case类中定义数据字段,并在伴生对象中定义业务逻辑。通过这种方式,您将数据与业务逻辑分离。

使用copy方法,您可以从源继承任何或所有必需的属性,并可以根据需要更改它们。

从技术上讲,类和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。