首页 文章

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

提问于
浏览
387

我在Google中搜索了 case classclass 之间的差异 . 每个人都提到当你想在类上进行模式匹配时,使用用例类 . 否则使用类,并提及一些额外的额外津贴,如equals和哈希码覆盖 . 但这些是为什么应该使用案例类而不是类的唯一原因?

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

14 回答

  • 339

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

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

    • 它创建一个类及其伴随对象

    • 其伴随对象实现了 apply 方法,您可以将其用作工厂方法 . 无需使用new关键字即可获得语法糖的优势 .


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

    • 默认情况下,您还可以获得 hashCodeequalstoString 方法, equals 方法在结构上比较对象 . 生成 copy 方法以能够克隆对象 .

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


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

  • 3

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

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

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

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

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

    [1] Case Classes Are Cool

    [2] Case Classes and Extractors, pg 15 .

  • 59

    类:

    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
    
  • 2
    • 案例类可以模式匹配

    • Case类自动定义hashcode和equals

    • Case类自动为构造函数参数定义getter方法 .

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

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

  • 0

    根据Scala的documentation

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

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

  • 0

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

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

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

  • 2

    我认为总体上所有的答案都给出了关于类和案例类的语义解释 . 这可能非常相关,但scala中的每个新手都应该知道在创建案例类时会发生什么 . 我写了this答案,简而言之解释了案例类 .

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

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

    refer this link if you want to check all the methods inside a case class .

  • 1
    • Case类使用apply和unapply定义compagnon对象方法

    • 案例类扩展了Serializable

    • Case类定义equals hashCode和copy方法

    • 构造函数的所有属性都是val(语法糖)

  • 24

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

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

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

  • 9

    没有人提到case类的伴随对象有 tupled defention,它有一个类型:

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

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

    val bobAsTuple = ("bob", 14)
    val bob = (Person.apply _).tupled(bobAsTuple) //bob: Person = Person(bob,14)
    

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

  • 150

    案例类是可以与 match/case 语句一起使用的类 .

    def isIdentityFun(term: Term): Boolean = term match {
      case Fun(x, Var(y)) if x == y => true
      case _ => false
    }
    

    你看到 case 后跟一个类Fun的实例,其第二个参数是Var . 这是一个非常好的和强大的语法,但它不能用于任何类的实例,因此对case类有一些限制 . 如果遵守这些限制,则可以自动定义哈希码和等号 .

    模糊的短语"a recursive decomposition mechanism via pattern matching"意味着“它适用于 case ” . (实际上, match 之后的实例与 case 之后的实例进行比较(匹配),Scala必须将它们分解,并且必须递归地分解它们的组成部分 . )

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

    什么案例类没用?有些对象有状态,像 connection.setConnectTimeout(connectTimeout) 这样的代码不适用于case类 .

    现在你可以阅读A Tour of Scala: Case Classes

  • 23

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

    1. Case Class 不需要显式 new ,而类需要用 new 调用
    val classInst = new MyClass(...)  // For classes
    val classInst = MyClass(..)       // For case class
    

    2.在 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
    
    1. 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
    
  • 2

    从技术上讲,类和案例类之间没有区别 - 即使编译器在使用案例类时确实优化了一些东西 . 但是,一个案例类用于取消特定模式的锅炉板,这正在实施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 .

  • 4

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

    这个功能概念允许我们

    • 使用紧凑的初始化语法( Node(1, Leaf(2), None))

    • 使用模式匹配对它们进行分解

    • 隐式定义了相等比较

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

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

相关问题