Scala的案例类和类之间有什么区别?

问题描述 投票:405回答:15

我在谷歌搜索找到case classclass之间的差异。每个人都提到当你想在类上进行模式匹配时,使用用例类。否则使用类并提及一些额外的额外津贴,如equals和hash code overriding。但这些是为什么应该使用案例类而不是类的唯一原因?

我想在Scala中这个功能应该有一些非常重要的原因。有什么解释或者是否有资源可以从中了解有关Scala案例类的更多信息?

scala functional-programming case-class
15个回答
371
投票

案例类可以看作是普通的和不可变的数据保持对象,它们应该完全取决于它们的构造函数参数。

这个功能概念允许我们

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

结合继承,case类用于模仿algebraic datatypes

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


3
投票

要最终了解什么是案例类:

让我们假设以下案例类定义:

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
  • 干将:
def foo(): String
def bar(): Int
  • 复制方法:
def copy(foo: String, bar: Int): Foo
def copy$default$1(): String
def copy$default$2(): Int
  • 实施scala.Product特质:
override def productPrefix(): String
def productArity(): Int
def productElement(x$1: Int): Object
override def productIterator(): Iterator
  • 通过scala.Equals为make case类实例实现== trait可比较的相等性:
def canEqual(x$1: Object): Boolean
override def equals(x$1: Object): Boolean
  • 为了遵守equals-hashcode合同而重写java.lang.Object.hashCode
override <synthetic> def hashCode(): Int
  • 压倒java.lang.Object.toString
override def toString(): String
  • new关键字实例化的构造函数:
def <init>(foo: String, bar: Int): Foo 

Object Foo: - 没有apply关键字的实例化方法new

case <synthetic> def apply(foo: String, bar: Int): Foo = new Foo(foo, bar);
  • 提取器方法unupply在模式匹配中使用case类Foo:
case <synthetic> def unapply(x$0: Foo): Option
  • 保护对象作为单例从反序列化保护的方法,不再生成一个实例:
<synthetic> private def readResolve(): Object = Foo;
  • 对象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

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

所以案例类只是语法糖。


2
投票

没人提到案例类伴侣对象有tupled defention,它有一个类型:

tupled

我能找到的唯一用例是当你需要从元组构造case类时,例如:

case class Person(name: String, age: Int)
//Person.tupled is def tupled: ((String, Int)) => Person

您可以通过直接创建对象来执行相同的操作,但是如果您的数据集表示为带有arity 20的元组列表(带有20个元素的元组),则可能正在使用tupled是您的选择。


2
投票

案例类是可以与val bobAsTuple = ("bob", 14) val bob = (Person.apply _).tupled(bobAsTuple) //bob: Person = Person(bob,14) 语句一起使用的类。

match/case

你看到def isIdentityFun(term: Term): Boolean = term match { case Fun(x, Var(y)) if x == y => true case _ => false } 后跟一个类Fun的实例,其第二个参数是Var。这是一个非常好的和强大的语法,但它不能用于任何类的实例,因此对case类有一些限制。如果遵守这些限制,则可以自动定义哈希码和等号。

模糊的短语“通过模式匹配的递归分解机制”意味着“它与case一起工作”。 (事实上​​,case之后的实例与match之后的实例进行了比较(匹配),Scala必须将它们分解,并且必须递归地分解它们的组成。)

什么案例类有用? case给出了两个很好的经典例子,列表和树。支持代数数据类型(包括知道如何比较它们)是任何现代函数语言的必备条件。

什么案例类没用?有些对象有状态,像Wikipedia article about Algebraic Data Types这样的代码不适用于case类。

现在你可以阅读connection.setConnectTimeout(connectTimeout)


2
投票

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

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

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


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

0
投票

我认为总的来说所有的答案都给出了关于类和案例类的语义解释。这可能非常相关,但scala中的每个新手都应该知道在创建案例类时会发生什么。我写了A Tour of Scala: Case Classes答案,简而言之解释了案例类。

每个程序员都应该知道,如果他们使用任何预先构建的函数,那么他们编写的代码相对较少,通过赋予编写最优化代码的能力来实现它们,但是功能带来了巨大的责任。因此,请谨慎使用预建功能。

一些开发人员由于额外的20种方法而避免编写案例类,您可以通过反汇编类文件看到这些方法。

this


0
投票

下面列出了refer this link if you want to check all the methods inside a case class的一些主要功能

  1. 案例类是不可变的。
  2. 您可以在不使用case classes关键字的情况下实例化案例类。
  3. 案例类可以按值进行比较

scala小提琴上的示例scala代码,取自scala文档。

new


157
投票

从技术上讲,类和案例类之间没有区别 - 即使编译器在使用案例类时确实优化了一些东西。但是,一个案例类用于取消特定模式的锅炉板,这是实施algebraic data types

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

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。


63
投票
  • 案例类可以模式匹配
  • 案例类自动定义哈希码和等号
  • 案例类自动为构造函数参数定义getter方法。

(你已经提到了除了最后一个之外的所有内容)。

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


27
投票

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

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

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


26
投票

没有人提到case类有val构造函数参数,但这也是常规类的默认值(在Scala的设计中是I think is an inconsistency)。达里奥暗示这样,他指出他们是“不可改变的”。

请注意,您可以通过在每个构造函数参数前加上var来为case类覆盖默认值。然而,使案例类可变导致他们的equalshashCode方法是时间变量。[1]

sepp2k已经提到过case类自动生成equalshashCode方法。

也没有人提到case类自动创建一个与该类同名的伴随object,它包含applyunapply方法。 apply方法可以在不预先添加new的情况下构建实例。 unapply提取器方法可以实现其他人提到的模式匹配。

此外,编译器优化了案例类的match-case模式匹配的速度[2]。

[1] Case Classes Are Cool

[2] Case Classes and Extractors, pg 15


9
投票

Scala中的case类构造也可以被视为删除一些样板的便利。

构建案例类时,Scala会为您提供以下内容。

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

因为类是不可变的,所以你得到的是访问器,它只是类的变量(或属性),但没有变异器(因此无法更改变量)。构造函数参数可自动作为公共只读字段使用。比Java bean构造好多了。

  • 你也可以默认获得hashCodeequalstoString方法,而equals方法在结构上比较一个对象。生成copy方法以能够克隆对象(具有向该方法提供新值的一些字段)。

前面提到的最大优点是你可以在案例类上进行模式匹配。这样做的原因是因为你得到了unapply方法,它允许你解构一个case类来提取它的字段。


实质上,在创建案例类时,您从Scala获得的内容(或者如果您的类不带参数,则是案例对象)是一个单例对象,用作工厂和提取器。


6
投票

除了人们已经说过的话,classcase class之间还有一些更基本的区别

1.Case Class不需要明确的new,而类需要用new调用

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

2.By默认构造函数参数在class中是私有的,而在case class中是公共的

// 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 class按价值比较自己

// case 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

5
投票

根据斯卡拉的documentation

案例类只是常规类:

  • 默认不可变
  • 可以通过pattern matching分解
  • 通过结构平等而不是通过引用进行比较
  • 简洁实例化和操作

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


4
投票

类:

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

人员类:

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
© www.soinside.com 2019 - 2024. All rights reserved.