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

Tej*_*eni 424 functional-programming scala case-class

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

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

Dar*_*rio 379

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

这个功能概念允许我们

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

结合继承,case类用于模拟代数数据类型.

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

  • @Teja:在某种程度上.ADT是有点*参数化的枚举*,非常强大且类型安全. (11认同)
  • 密封案例类用于模拟代数数据类型.否则,子类的数量不受限制. (8认同)
  • @Thomas:正确地说,从密封的抽象类派生的*case类模仿闭合的代数数据类型*而ADT否则*open*. (6认同)
  • @Dario ...而且该类型是开放的而不是ADT.:-) (2认同)
  • *[...] 普通且不可变的数据保存对象 [...]* 请注意,Scala 不强制 case 类的不变性:`case class Foo(var int: Int)`。 (2认同)

Dan*_*ral 159

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

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

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
Run Code Online (Sandbox Code Playgroud)

这使我们能够做到以下几点:

// 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 =>
}
Run Code Online (Sandbox Code Playgroud)

请注意,树构造和解构(通过模式匹配)使用相同的语法,这也正是它们的打印方式(减去空格).

它们也可以与哈希映射或集合一起使用,因为它们具有有效,稳定的hashCode.


sep*_*p2k 66

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

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

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

  • 除非在构造函数参数中指定了"var",否则不会为case类生成setter,在这种情况下,您将获得与常规类相同的getter/setter生成. (12认同)

Jea*_*let 28

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

def productElement(n: Int): Any
def productArity: Int
def productIterator: Iterator[Any]
Run Code Online (Sandbox Code Playgroud)

其中productArity返回的类的参数的数量,productElement(i)返回参数,并productIterator允许通过迭代他们.

  • 但是,它们不是Product1,Product2等的实例。 (2认同)

She*_*III 26

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

请注意,您可以通过var为case类添加每个构造函数参数来覆盖缺省值.但是,使案例类可变会导致它们equalshashCode方法成为时间变量.[1]

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

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

还编译器优化的速度match- case图案为case类[2]的匹配.

[1] 案例类很酷

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


Fak*_* 10 9

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

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

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

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

  • 默认情况下,您还可以获取hashCode,equalstoString方法,并且该equals方法在结构上比较对象.copy生成一种能够克隆对象的方法(某些字段具有提供给该方法的新值).

前面提到的最大优点是你可以在案例类上进行模式匹配.这样做的原因是因为您获得了unapply允许您解构案例类以提取其字段的方法.


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


Mat*_* I. 8

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

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

case class Foo(foo:String, bar: Int)
Run Code Online (Sandbox Code Playgroud)

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

$ scalac -print src/main/scala/Foo.scala
Run Code Online (Sandbox Code Playgroud)

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>();
    ()
  }
}
...
Run Code Online (Sandbox Code Playgroud)

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

让我们通过编译的类并评论我们得到的东西:

  • 类的内部状态Foo,不可变:
val foo: String
val bar: Int
Run Code Online (Sandbox Code Playgroud)
  • 吸气剂:
def foo(): String
def bar(): Int
Run Code Online (Sandbox Code Playgroud)
  • 复制方法:
def copy(foo: String, bar: Int): Foo
def copy$default$1(): String
def copy$default$2(): Int
Run Code Online (Sandbox Code Playgroud)
  • 实现scala.Product特性:
override def productPrefix(): String
def productArity(): Int
def productElement(x$1: Int): Object
override def productIterator(): Iterator
Run Code Online (Sandbox Code Playgroud)
  • 通过以下方式实现scala.Equals使案例类实例具有可比性的特征==
def canEqual(x$1: Object): Boolean
override def equals(x$1: Object): Boolean
Run Code Online (Sandbox Code Playgroud)
  • java.lang.Object.hashCode为遵守 equals-hashcode 合同而重写:
override <synthetic> def hashCode(): Int
Run Code Online (Sandbox Code Playgroud)
  • 覆盖java.lang.Object.toString
override def toString(): String
Run Code Online (Sandbox Code Playgroud)
  • 通过new关键字实例化的构造函数:
def <init>(foo: String, bar: Int): Foo 
Run Code Online (Sandbox Code Playgroud)

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

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

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

所以案例类只是语法糖。


小智 7

除了人们已经说过,之间存在一些更基本的差异classcase class

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

val classInst = new MyClass(...)  // For classes
val classInst = MyClass(..)       // For case class
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)


use*_*782 6

班级:

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
           ^
Run Code Online (Sandbox Code Playgroud)

但是如果我们使用相同的代码但用例类:

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
Run Code Online (Sandbox Code Playgroud)

人物类:

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)
Run Code Online (Sandbox Code Playgroud)

模式匹配:

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
Run Code Online (Sandbox Code Playgroud)

对象:单例:

scala> case class Person(first :String,last:String,age:Int)
defined class Person

scala> object Fred extends Person("Fred","Jones",22)
defined object Fred
Run Code Online (Sandbox Code Playgroud)


小智 5

根据Scala的文档:

案例类只是常规类:

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

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