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

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


当前回答

在之前的回答中没有提到的一个重要问题是身份。常规类的对象具有同一性,因此即使两个对象的所有字段值相同,它们仍然是不同的对象。然而,对于case类实例,相等性纯粹是根据对象字段的值定义的。

其他回答

没有人提到case类有val构造函数参数,但这也是常规类的默认值(我认为这是Scala设计中的不一致)。达里奥暗示了这一点,他指出它们是“不可改变的”。

注意,可以通过在每个构造函数参数前加上var来覆盖默认值。然而,使case类可变会导致它们的equals和hashCode方法是时变的

sepp2k已经提到case类自动生成equals和hashCode方法。

同样没有人提到case类会自动创建一个与类同名的伴生对象,其中包含apply和unapply方法。apply方法允许在不使用new前置的情况下构造实例。unapply提取器方法启用了其他人提到的模式匹配。

此外,编译器还优化了大小写类[2]的匹配大小写模式匹配速度。

案例类很酷

[2]案例类和提取器,第15页。

Case类可以被看作是普通的、不可变的数据保存对象,应该完全依赖于它们的构造函数参数。

这个函数概念允许我们

使用紧凑的初始化语法(Node(1, Leaf(2), None))) 使用模式匹配分解它们 是否隐含地定义了相等比较

结合继承,case类被用来模拟代数数据类型。

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

要最终理解什么是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类的一些关键特性

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

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

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

根据Scala的文档:

Case类只是常规类,它们是: 默认是不可变的 可通过模式匹配进行分解 用结构相等代替参照进行比较 简单的实例化和操作

case关键字的另一个特性是编译器自动为我们生成几个方法,包括Java中熟悉的toString、equals和hashCode方法。