我在谷歌搜索找到a case class
和a 之间的差异class
。每个人都提到当你想在类上进行模式匹配时,使用用例类。否则使用类并提及一些额外的额外津贴,如equals和hash code overriding。但这些是为什么应该使用案例类而不是类的唯一原因?
我想在Scala中这个功能应该有一些非常重要的原因。有什么解释或者是否有资源可以从中了解有关Scala案例类的更多信息?
案例类可以看作是普通的和不可变的数据保持对象,它们应该完全取决于它们的构造函数参数。
这个功能概念允许我们
使用紧凑的初始化语法(Node(1, Leaf(2), None))
)
使用模式匹配来分解它们
有隐含地定义的相等比较
结合继承,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。
没有人提到案例类也是Product这些方法的实例并因此继承这些方法:
def productElement(n: Int): Any
def productArity: Int
def productIterator: Iterator[Any]
其中productArity返回的类的参数的数量,productElement(i)返回我个参数,并productIterator允许通过迭代他们。
举报