scala案例

发表简短目录 (Post Brief TOC)

  • Introduction介绍
  • What is Case Class什么是案例类
  • What is Case Object什么是案例对象
  • Scala’s Case Class Benefit-1Scala的案例类权益-1
  • Scala’s Case Class Benefit-2Scala案例类别Benefit-2
  • Scala’s Case Class Benefit-3Scala案例类权益3
  • Scala’s Case Class Benefit-4Scala案例类别Benefit-4
  • Scala’s Case Class Benefit-5Scala案例类别Benefit-5
  • Scala’s Case Class Benefits In BriefScala案例类的好处简述
  • Drawback of Scala’s Case Class/ObjectScala案例类/对象的缺点

介绍 (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:

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

  • Case Class and Case Object Basics案例类和案例对象基础
  • Case Class and Case Object Advanced Concepts案例类和案例对象高级概念

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 Personscala> 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 Personscala> val person1 = Person("Posa",30)
person1: Person = Person(Posa,30)scala> person1.name
res0: String = Posascala> person1.age
res1: Int = 30scala> person1.age = 32
:13: error: reassignment to valperson1.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 Studentscala> 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 Studentscala> 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案例

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

  1. C++_类和对象_封装_案例_立方体类_案例点和圆的关系---C++语言工作笔记039

  2. C++多态案例一计算器类

    C++多态案例一计算器类 多态案例一计算器类 案例描述 多态的优点 示例 多态案例一计算器类 案例描述 分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类 多态的优点 代码组织结构清晰 ...

  3. scala案例_Scala案例类和案例对象深入(第2部分)

    scala案例 发表简短目录 (Post Brief TOC) Introduction介绍 Scala's Case Class Benefit-6Scala案例类权益6 Advantages of ...

  4. java写一个外网访问的接口_【JAVA基础】一个案例搞懂类、对象、重载、封装、继承、多态、覆盖、抽象和接口概念及区别(中篇)...

    0 前言 初学JAVA时,总会对一些概念一知半解,相互混淆,不明其设计的用意,如类.对象.重载.封装.继承.多态.覆盖.抽象类.接口概念.为便于理解和巩固,本文将基于一个案例及其变形,展现各个概念的定 ...

  5. Java中构造方法的案例及常用类int lenght类的使用方法举例,new实例化对象方法,静态方法实例方法的举例

    目录 一.前言 二.构造方法的案例 2.1代码部分 2.2运行截图 三.常用类int lenght类的使用方法举例 3.1程序代码 3.2运行结果 四.new实例化对象方法例题 4.1程序代码 4.2 ...

  6. 学习集合工具类CollectionUtils——List对象案例

    学习集合工具类CollectionUtils--List对象案例 一.依赖 二.案例 三.结果展示 一.依赖 <dependency><groupId>org.apache.c ...

  7. Day18JavaSE——Map集合Collections工具类集合案例练习

    Day18JavaSE--Map集合&Collections工具类&集合案例练习 文章目录 Day18JavaSE--Map集合&Collections工具类&集合案例 ...

  8. 软件方法(下)分析和设计第9章分析 之 分析类图——案例篇(20211228更新)

    软件方法(下)分析和设计第8章分析 之 分析类图--知识篇(20211227更新) 鸳鸯扣,宜结不宜解 <身似摇红烛影>,词:唐涤生,曲:王粤生,唱:红线女,1954 可到此处下载本文档最 ...

  9. Netty消息接收类故障案例分析

    <Netty 进阶之路>.<分布式服务框架原理与实践>作者李林锋深入剖析Netty消息接收类故障案例.李林锋此后还将在 InfoQ 上开设 Netty 专题持续出稿,感兴趣的同 ...

最新文章

  1. 3.过滤数据 ---SQL
  2. html window 属性,html中window对象top 、self 、parent 等属性
  3. 中国男性的私密数据分析……
  4. 一段顺序颠倒能读通的文字_钓鱼也有逻辑顺序,总是钓不到鱼的原因就在这里...
  5. [DB]MariaDB 与 MySql 数据库
  6. linux内存管理源码分析 - 页框分配器
  7. Ubuntu/Linux/Unix 究竟有什么区别??
  8. MOEA/D的通俗解析--1.MOEA
  9. Ubuntu18.04 打不开系统蓝牙适配器,也连接不上任何蓝牙设备Bug解决方案
  10. 【seeprettyface.com】数据集:模特/明星人脸数据集
  11. PHP实现汉字转拼音
  12. IDA Pro与x64dbg联动调试记录
  13. 【从面试出发学习java】- 缓存 - Redis面试题
  14. C++基本功和 Design Pattern系列 Operator 下
  15. 从哪里租vps远程桌面服务器,vps远程桌面服务器出租
  16. 【NoteBook】刘润:新零售:低价高效的数据赋能之路
  17. 2018年网络安全大事记
  18. IE浏览器下载文件名乱码
  19. 今天接到一个诈骗电话!!!原来有这么多的受害者
  20. BetaFlight模块设计之三十:Cli模块分析

热门文章

  1. 用户控件页为什么找不到.ClientScript.RegisterClientScriptBlock原因
  2. System.IO.Directory.Delete 方法的使用
  3. 如何使用JavaScript阻止关闭窗口
  4. [转载] Python字典及基本操作(超级详细)
  5. [转载] 【Python进阶】4-2 多态 | 什么是多态 / 静态语言vs动态语言 / python中多态
  6. [转载] 比较器(Comparable和Comparator)、自然排序、定制排序
  7. Capital Asset Pricing Model (CAPM)
  8. 从后台获取的数据渲染到页面中的dom操作
  9. 详解k8s一个完整的监控方案(Heapster+Grafana+InfluxDB) - kubernetes
  10. 在centos下安装django