scala案例_Scala案例类和案例对象深入(第1部分)

scala案例

发表简短目录 (Post Brief TOC)

  • Introduction

    介绍
  • What is Case Class

    什么是案例类
  • What is Case Object

    什么是案例对象
  • Scala’s Case Class Benefit-1

    Scala的案例类权益-1
  • Scala’s Case Class Benefit-2

    Scala案例类别Benefit-2
  • Scala’s Case Class Benefit-3

    Scala案例类权益3
  • Scala’s Case Class Benefit-4

    Scala案例类别Benefit-4
  • Scala’s Case Class Benefit-5

    Scala案例类别Benefit-5
  • Scala’s Case Class Benefits In Brief

    Scala案例类的好处简述
  • Drawback of Scala’s Case Class/Object

    Scala案例类/对象的缺点

介绍 (Introduction)

In this post, we are going to discuss about one of the important concept of Scala Language: Case Class and Case Object.

在本文中,我们将讨论Scala语言的重要概念之一:案例类和案例对象。

The main advantage or aim of Case Class concept is that to ease the development by avoiding lot of boilerplate code. We can use Case Classes in Pattern Matching very easily.

案例类概念的主要优点或目的是通过避免大量样板代码来简化开发。 我们可以很容易地在模式匹配中使用案例类。

As this concept is very important, I’m going to deliver this into two different posts:

由于这个概念非常重要,因此我将其介绍给两个不同的职位:

We will discuss “Case Class and Case Object Basics” in detail in this post with some suitable examples. Will deliver one more post for some advanced concepts.

我们将在本文中通过一些合适的示例详细讨论“案例类和案例对象基础”。 将再发布一些高级概念的文章。

什么是案例类? (What is Case Class?)

Case class is also a class, which is defined with “case” modifier. Because of this “case” keyword, we will get some benefits to avoid boilerplate code.

案例类也是一个用“案例”修饰符定义的类。 由于使用了“ case”关键字,我们将获得一些避免样板代码的好处。

Example:-

例:-

scala> case class Employee(name:String)
defined class Employee

Here we have defined a case class with name “Employee” and with one parameter “name”.

在这里,我们定义了一个案例类,名称为“ Employee”,参数为“ name”。

什么是案例对象? (What is Case Object?)

Case object is also an object which is defined with “case” modifier. Because of this “case” keyword, we will get some benefits to avoid boilerplate code.

案例对象也是使用“案例”修饰符定义的对象。 由于使用了“ case”关键字,我们将获得一些避免样板代码的好处。

Example:-

例:-

scala> case object Employee
defined object Employee

Here we have defined a case object with name “Employee”.

在这里,我们定义了一个名称为“ Employee”的案例对象。

Let us explore the benefits of Case Classes in-detail with examples.

让我们通过示例详细探讨案例类的好处。

Scala的案例类权益-1 (Scala’s Case Class Benefit-1)

First and foremost benefit of Case Class is that Scala Compiler adds a factory method with the name of the class with same number of parameters defined in the class definition.

Case类的首要优势是Scala编译器添加了一个工厂方法,该方法的类名与在类定义中定义的参数数量相同。

Because of this benefit, we can create objects of the Case Class without using “new” keyword.

因此,我们无需使用“ new”关键字就可以创建Case类的对象。

Example:-

例:-

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

scala> val person1 = Person("Posa",30)
person1: Person = Person(Posa,30)

scala> val person2 = new Person("Posa",30)
person2: Person = Person(Posa,30)

If we observe above code snippet, we can create Case class objects without using “new” keyword. It is also allowed “new” keyword, but not recommended to use it here.

如果我们观察以上代码片段,则可以创建Case类对象,而无需使用“ new”关键字。 还允许使用“ new”关键字,但不建议在此处使用它。

Scala案例类别Benefit-2 (Scala’s Case Class Benefit-2)

By default, Scala compiler prefixes “val” for all constructor parameters. That’s why without using val or var, Case class’s constructor parameters will become class members, it is not possible for normal classes.

默认情况下,Scala编译器为所有构造函数参数添加“ val”前缀。 这就是为什么不使用val或var的情况下,Case类的构造函数参数将成为类成员,而普通类则不可能。

Example:-

例:-

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

scala> val person1 = Person("Posa",30)
person1: Person = Person(Posa,30)

scala> person1.name
res0: String = Posa

scala> person1.age
res1: Int = 30

scala> person1.age = 32
:13: error: reassignment to val
       person1.age = 32
                   ^

By observing above example, we can say that Case class constructor parameters are by default val. We cannot reassign a new value to them once that class object is created. We can access their values by using getter methods, but they don’t have setter methods.

通过观察上面的示例,我们可以说Case类的构造函数参数默认为val。 创建该类对象后,我们无法为它们重新分配新值。 我们可以使用getter方法访问它们的值,但是它们没有setter方法。

NOTE:- Before discussing the next benefit, we need to understand one point about Case classes.
When we compile a Case class using scalac, what will happen? How many “*.class” files are generated for one Case classes? What are they?

注意:-在讨论下一个好处之前,我们需要了解关于案例类的一点。
当我们使用scalac编译Case类时,会发生什么? 一个Case类生成了多少个“ * .class”文件? 这些是什么?

Let us explore this with a simple example:

让我们通过一个简单的示例对此进行探讨:

  • Create a Case class in a source file as shown below

    在源文件中创建Case类,如下所示
  • Person.scala

    人标

case class Person(name:String, age:Int)

Here we can observe that only one source file “Persona.scala” is available.

在这里我们可以看到只有一个源文件“ Persona.scala”可用。

  • Open a CMD prompt and compile this source file with scalac as shown below

    打开CMD提示符,并使用scalac编译此源文件,如下所示
  • Here we can observe that Scala Compiler has generated two class files: “Person.class” and “Person$.class”

    在这里我们可以看到Scala编译器已经生成了两个类文件:“ Person.class”和“ Person $ .class”

    NOTE:- We will get similar kind of two classes even for Case Objects.

    注意:-即使对于Case Objects,我们也会得到类似的两个类。

    Scala案例类权益3 (Scala’s Case Class Benefit-3)

    It is most important feature and very useful. Scala compiler automatically adds “Default Implementation” to toString, hashCode and equals and copy methods.

    这是最重要的功能,非常有用。 Scala编译器会自动将“默认实现”添加到toString,hashCode以及equals和copy方法。

    We can observe this in the following diagram.

    我们可以在下图中观察到这一点。

    Scala案例类别Benefit-4 (Scala’s Case Class Benefit-4)

    Scala compiler also adds a copy method to Case class automatically. It is used to create a copy of same instance with modifying few attributes or without modifying it.

    Scala编译器还自动将复制方法添加到Case类。 它用于创建同一实例的副本,而只需修改几个属性或不修改它。

    We can observe this feature in the above diagram.

    我们可以在上图中观察到此功能。

    Example-1:- To create a new copy of same object without changing the object attributes.

    示例1:-在不更改对象属性的情况下创建同一对象的新副本。

    scala> case class Student(name:String, marks:Int)
    defined class Student
    
    scala> val s1 = Student("Rams",550)
    s1: Student = Student(Rams,550)
    
    scala> val s2 = s1.copy()
    s2: Student = Student(Rams,550)

    Here, we have created new object s2 by using copy method on s1 object without changing s1 object attributes. That means both are equal as shown below:

    在这里,我们通过在s1对象上使用复制方法创建了新的对象s2,而没有更改s1对象的属性。 这意味着两者相等,如下所示:

    scala> s1 == s2
    res3: Boolean = true

    Example:- To create a new copy of same object with changing the object attributes.

    示例:-通过更改对象属性创建相同对象的新副本。

    scala> case class Student(name:String, marks:Int)
    defined class Student
    
    scala> val s1 = Student("Rams",550)
    s1: Student = Student(Rams,550)
    
    scala> val s3 = s1.copy(marks=590)
    s3: Student = Student(Rams,590)

    NOTE:- Here we are using Scala’s Named Parameter Feature. Please read my Scala’s Named Parameter tutorial to understand it well.

    注意:-这里我们使用Scala的命名参数功能。 请阅读我的Scala的命名参数教程,以更好地理解它。

    Here, we have created new object s3 by using copy method on s1 object without changing s1 object attributes. That means both are NOT equal as shown below:

    在这里,我们通过对s1对象使用复制方法创建了新对象s3,而没有更改s1对象属性。 这意味着两者不相等,如下所示:

    scala> s1 == s3
    res3: Boolean = false

    Scala案例类别Benefit-5 (Scala’s Case Class Benefit-5)

    Scala compiler also creates a companion object to that Case class and adds apply and unapply methods. We can observe this in the following diagram.

    Scala编译器还会为该Case类创建一个伴随对象,并添加apply和unapply方法。 我们可以在下图中观察到这一点。

    Example:-
    If we create a Case Class as shown below:

    例:-
    如果我们创建一个Case类,如下所示:

    case class Person(name:String)

    Scala Compiler adds a Companion Object with apply and unapply methods as shown below:

    Scala编译器添加了一个带有apply和unapply方法的Companion对象,如下所示:

    object Person{
       def unapply(p:Person):Option[String] = Some(p.name)
       def apply(name:String):Person = new Person(name)
    }

    So far, we have discussed what are the benefits of Scala’s Case Class. I’m going to list out all those benefits one by one in brief in next section.

    到目前为止,我们已经讨论了Scala案例类的好处。 我将在下一节中简要列出所有这些好处。

    NOTE:- Java does NOT have Case class or Case object concept.

    注意: Java没有Case类或Case对象的概念。

    Scala案例类的好处简述 (Scala’s Case Class Benefits In Brief)

    Case class is also a class, however when we compare it with normal class, it gives us some extra features or benefits.

    案例类也是一类,但是当我们将其与普通类进行比较时,它为我们提供了一些额外的功能或好处。

    The following are the complete list of Advantages/Benefits of Scala’s Case class:

    以下是Scala Case类的优点/好处的完整列表:

    • By default, Scala Compiler adds toString, hashCode and equals methods. We can avoid writing this boilerplate code.

      默认情况下,Scala编译器添加toString,hashCode和equals方法。 我们可以避免编写此样板代码。
    • By default, Scala Compiler adds companion object with apply and unapply methods that’s why we don’t need new keyword to create instances of a case class.

      默认情况下,Scala编译器添加带有apply和unapply方法的伴随对象,这就是为什么我们不需要new关键字来创建case类的实例的原因。
    • By default, Scala Compiler adds copy method too.

      默认情况下,Scala编译器也会添加复制方法。
    • We can use case classes in Pattern Matching.

      我们可以在模式匹配中使用案例类。
    • By default, Case class and Case Objects are Serializable.

      默认情况下,Case类和Case对象是可序列化的。
    • By using Case Classes, we can define Algebraic data types (ADT).

      通过使用案例类,我们可以定义代数数据类型(ADT)。
    • They improve productivity that means it avoids writing lot of boilerplate code so that Developers can deliver a functionality with less effort.

      它们提高了生产率,这意味着它避免了编写大量样板代码,从而使开发人员可以更轻松地交付功能。

    All these features are added by Scala Compiler at compile-time. It is not possible with normal class.

    所有这些功能都是由Scala编译器在编译时添加的。 普通班不可能。

    Scala案例类/对象的缺点 (Drawback of Scala’s Case Class/Object)

    As we discussed in the above section, Scala’s Case Class/Object have many benefits. They ease the Development process and improve the the Productivity. However they have only few drawbacks and they are ignorable:

    正如我们在上一节中讨论的那样,Scala的Case类/对象有很多好处。 它们简化了开发过程并提高了生产率。 但是,它们只有很少的缺点,并且可以忽略:

    • As Scala compiler adds lots of boilerplate code for us, compiled class file size is bit more and may have more byte code. If we don’t want to use those default method implementations for equals, toString etc, in that case only we can say it is not useful.

      由于Scala编译器为我们添加了许多样板代码,因此编译后的类文件大小会更多一些,并且可能会有更多的字节代码。 如果我们不想将这些默认方法实现用于equals,toString等,那么在那种情况下,我们只能说它没有用。
    • Scala Compiler adds some additional functionality by extending scala.Product trait. Most of the time, it is not useful.

      Scala编译器通过扩展scala.Product特性增加了一些附加功能。 大多数时候,它是没有用的。
    • If we see compiled class using any Java/Scala Decompiler, we can observe the following code snippet.

      如果我们看到使用任何Java / Scala Decompiler编译的类,则可以观察以下代码段。

    public class Person implements scala.Product ... {
     // Some methods are inherited from Product trait
    }

    That’s it all about Scala Case Class and Case Object Basics. We will discuss Scala Case Class and Case Object Advanced concepts in my coming posts.

    这就是有关Scala Case类和Case对象基础的全部内容。 我们将在我的后续文章中讨论Scala案例类和案例对象高级概念。

    Please drop me a comment if you like my post or have any issues/suggestions.

    如果您喜欢我的帖子或有任何问题/建议,请给我评论。

    翻译自: https://www.journaldev.com/9733/scala-caseclass-caseobject-part1

    scala案例

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
第1章,“可伸展的语言”,给出了Scala的设计,和它后面的理由,历史的概要。 第2章,“Scala的第一步”,展示给你如何使用Scala完成若干种基本编程任务,而不牵涉过多关于如何工作的细节。本章的目的是让你的手指开始敲击并执行Scala代码。 第3章,“Scala的下一步”,演示更多的基本编程任务来帮助你更快速地上手Scala。本章之后,你将能够开始在简单的脚本任务中使用Scala。 第4章,“对象”,通过描述面向对象语言的基本建设模块和如何编译及运行Scala程序的教程开始有深度地覆盖Scala语言。 第5章,“基本型和操作”,覆盖了Scala的基本型,它们的文本,你可以执行的操作,优先级和关联性是如何工作的,还有什么是富包装器。 第6章,“函数式对象”,进入了Scala面向对象特征的更深层次,使用函数式(即,不可变)分数作为例子。 第7章,“内建控制结构”,显示了如何使用Scala的内建控制结构,如,if,while,for,try和match。 第8章,“函数和闭包”,深度讨论了函数式语言的基础建设模块,函数。 ...... 第31章,“组合子解析”,显示了如何使用Scala的解析器组合子库来创建解析器。 第32章,“GUI编程”,展示了使用Scala库简化基于Swing的GUI编程的快速旅程。 第33章,“SCell电子表”,通过展示一个完整的电子表的实现,集中演示了Scala的一切。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值