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

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


当前回答

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

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

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

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

其他回答

要最终理解什么是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类是可以与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

Case类用apply和unapply方法定义一个compagnon对象 Case类扩展了Serializable Case类定义了equals hashCode和copy方法 构造函数的所有属性都是val(语法糖)

从技术上讲,类和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类是不可变的。 可以实例化case类而不需要new关键字。 案例类可以根据值进行比较

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

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