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

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


当前回答

要最终理解什么是case类:

让我们假设下面的case类定义:

case class Foo(foo:String, bar: Int)

然后在终端中执行以下操作:

$ scalac -print src/main/scala/Foo.scala

Scala 2.12.8将输出:

...
case class Foo extends Object with Product with Serializable {

  <caseaccessor> <paramaccessor> private[this] val foo: String = _;

  <stable> <caseaccessor> <accessor> <paramaccessor> def foo(): String = Foo.this.foo;

  <caseaccessor> <paramaccessor> private[this] val bar: Int = _;

  <stable> <caseaccessor> <accessor> <paramaccessor> def bar(): Int = Foo.this.bar;

  <synthetic> def copy(foo: String, bar: Int): Foo = new Foo(foo, bar);

  <synthetic> def copy$default$1(): String = Foo.this.foo();

  <synthetic> def copy$default$2(): Int = Foo.this.bar();

  override <synthetic> def productPrefix(): String = "Foo";

  <synthetic> def productArity(): Int = 2;

  <synthetic> def productElement(x$1: Int): Object = {
    case <synthetic> val x1: Int = x$1;
        (x1: Int) match {
            case 0 => Foo.this.foo()
            case 1 => scala.Int.box(Foo.this.bar())
            case _ => throw new IndexOutOfBoundsException(scala.Int.box(x$1).toString())
        }
  };

  override <synthetic> def productIterator(): Iterator = scala.runtime.ScalaRunTime.typedProductIterator(Foo.this);

  <synthetic> def canEqual(x$1: Object): Boolean = x$1.$isInstanceOf[Foo]();

  override <synthetic> def hashCode(): Int = {
     <synthetic> var acc: Int = -889275714;
     acc = scala.runtime.Statics.mix(acc, scala.runtime.Statics.anyHash(Foo.this.foo()));
     acc = scala.runtime.Statics.mix(acc, Foo.this.bar());
     scala.runtime.Statics.finalizeHash(acc, 2)
  };

  override <synthetic> def toString(): String = scala.runtime.ScalaRunTime._toString(Foo.this);

  override <synthetic> def equals(x$1: Object): Boolean = Foo.this.eq(x$1).||({
      case <synthetic> val x1: Object = x$1;
        case5(){
          if (x1.$isInstanceOf[Foo]())
            matchEnd4(true)
          else
            case6()
        };
        case6(){
          matchEnd4(false)
        };
        matchEnd4(x: Boolean){
          x
        }
    }.&&({
      <synthetic> val Foo$1: Foo = x$1.$asInstanceOf[Foo]();
      Foo.this.foo().==(Foo$1.foo()).&&(Foo.this.bar().==(Foo$1.bar())).&&(Foo$1.canEqual(Foo.this))
  }));

  def <init>(foo: String, bar: Int): Foo = {
    Foo.this.foo = foo;
    Foo.this.bar = bar;
    Foo.super.<init>();
    Foo.super./*Product*/$init$();
    ()
  }
};

<synthetic> object Foo extends scala.runtime.AbstractFunction2 with Serializable {

  final override <synthetic> def toString(): String = "Foo";

  case <synthetic> def apply(foo: String, bar: Int): Foo = new Foo(foo, bar);

  case <synthetic> def unapply(x$0: Foo): Option =
     if (x$0.==(null))
        scala.None
     else
        new Some(new Tuple2(x$0.foo(), scala.Int.box(x$0.bar())));

  <synthetic> private def readResolve(): Object = Foo;

  case <synthetic> <bridge> <artifact> def apply(v1: Object, v2: Object): Object = Foo.this.apply(v1.$asInstanceOf[String](), scala.Int.unbox(v2));

  def <init>(): Foo.type = {
    Foo.super.<init>();
    ()
  }
}
...

正如我们所看到的,Scala编译器生成了一个常规类Foo和伴生对象Foo。

让我们浏览编译后的类,并对我们得到的内容进行注释:

Foo类的内部状态,不可变:

val foo: String
val bar: Int

getter方法:

def foo(): String
def bar(): Int

方法:复制

def copy(foo: String, bar: Int): Foo
def copy$default$1(): String
def copy$default$2(): Int

scala实现。产品特点:

override def productPrefix(): String
def productArity(): Int
def productElement(x$1: Int): Object
override def productIterator(): Iterator

scala实现。通过==使case类实例具有相等可比性的Equals trait:

def canEqual(x$1: Object): Boolean
override def equals(x$1: Object): Boolean

重写java.lang.Object.hashCode以遵守equals-hashcode契约:

override <synthetic> def hashCode(): Int

重写java.lang.Object.toString:

override def toString(): String

使用new关键字实例化的构造函数:

def <init>(foo: String, bar: Int): Foo 

对象Foo: 不带new关键字的实例化方法:

case <synthetic> def apply(foo: String, bar: Int): Foo = new Foo(foo, bar);

在模式匹配中使用case类Foo的提取器方法unsupply:

case <synthetic> def unapply(x$0: Foo): Option

方法来保护对象作为单例对象不被反序列化,以免产生更多实例:

<synthetic> private def readResolve(): Object = Foo;

object Foo扩展了scala.runtime.AbstractFunction2来做这样的事情:

scala> case class Foo(foo:String, bar: Int)
defined class Foo

scala> Foo.tupled
res1: ((String, Int)) => Foo = scala.Function2$$Lambda$224/1935637221@9ab310b

tupled from object返回一个函数,通过应用2个元素的元组来创建一个新的Foo。

所以case类只是语法糖。

其他回答

我认为总的来说,所有的答案都给出了一个关于类和case类的语义解释。 这可能非常相关,但是scala的每个新手都应该知道创建case类时会发生什么。我写了这个答案,简要地解释了案例类。

每个程序员都应该知道,如果他们使用任何预先构建的函数,那么他们编写的代码相对较少,这使他们能够编写最优化的代码,但能力伴随着巨大的责任。因此,使用预构建函数时要非常小心。

一些开发人员避免编写case类,因为有额外的20个方法,这可以通过分解类文件看到。

如果您想查看case类中的所有方法,请参考此链接。

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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