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类用于模拟代数数据类型.
如果一个对象在内部执行有状态计算或表现出其他类型的复杂行为,它应该是一个普通的类.
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
(你已经提到了除了最后一个之外的所有内容).
这是与常规课程的唯一区别.
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允许通过迭代他们.
She*_*III 26
没有人提到case类有val构造函数参数,但这也是常规类的默认值(我认为这是 Scala设计中的一个不一致).达里奥暗示这样,他指出他们是" 不可改变的 ".
请注意,您可以通过var为case类添加每个构造函数参数来覆盖缺省值.但是,使案例类可变会导致它们equals和hashCode方法成为时间变量.[1]
sepp2k已经提到过case类自动生成equals和hashCode方法.
也没有人提到case类自动创建一个object与类同名的伴随,包含apply和unapply方法.该apply方法可以在不预先添加的情况下构建实例new.该unapply提取方法使得别人提到的模式匹配.
还编译器优化的速度match- case图案为case类[2]的匹配.
[1] 案例类很酷
[2] 案例类和提取器,第15页.
Scala中的case类构造也可以被视为删除一些样板的便利.
构建案例类时,Scala会为您提供以下内容.
apply您可以用作工厂方法的方法.您可以获得不必使用new关键字的语法糖优势.
因为类是不可变的,所以你得到的是访问器,它只是类的变量(或属性),但没有变异器(因此无法更改变量).构造函数参数可自动作为公共只读字段使用.比Java bean构造好多了.
hashCode,equals和toString方法,并且该equals方法在结构上比较对象.copy生成一种能够克隆对象的方法(某些字段具有提供给该方法的新值).前面提到的最大优点是你可以在案例类上进行模式匹配.这样做的原因是因为您获得了unapply允许您解构案例类以提取其字段的方法.
实质上,在创建案例类时,您从Scala获得的内容(或者如果您的类不带参数,则是案例对象)是一个单独的对象,用作工厂和提取器.
要最终了解什么是案例类:
让我们假设以下案例类定义:
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)
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
除了人们已经说过,之间存在一些更基本的差异class和case 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)
班级:
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)
| 归档时间: |
|
| 查看次数: |
108647 次 |
| 最近记录: |