kotlin数据类

In this tutorial, we’ll look at Kotlin Data Class. If you haven’t read the Kotlin Classes post, we recommend you to do so before proceeding.

在本教程中,我们将研究Kotlin数据类。 如果您还没有阅读Kotlin Classes帖子,我们建议您在继续之前阅读。

Kotlin数据类 (Kotlin Data Class)

Do you get tired of writing thousands of lines of code for your POJO data classes in Java?

您是否厌倦了用Java为POJO数据类编写数千行代码?

Every Java Programmer at some stage must have taken a note of the number of lines of code they need to write for classes that just need to store some data. Let’s see how a Book.java POJO class looks like:

每个Java程序员在某个阶段都必须记下他们需要为只需要存储一些数据的类编写的代码行数。 让我们看看Book.java POJO类的样子:

public class Book {private String name;private String authorName;private long lastModifiedTimeStamp;private float rating;private int downloads;public Book(String name, String authorName, long lastModified, float rating, int downloads) {this.name = name;this.authorName = authorName;this.lastModifiedTimeStamp = lastModified;this.rating = rating;this.downloads = downloads;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthorName() {return authorName;}public void setAuthorName(String authorName) {this.authorName = authorName;}public long getLastModifiedTimeStamp() {return lastModifiedTimeStamp;}public void setLastModifiedTimeStamp(long lastModifiedTimeStamp) {this.lastModifiedTimeStamp = lastModifiedTimeStamp;}public float getRating() {return rating;}public void setRating(float rating) {this.rating = rating;}public int getDownloads() {return downloads;}public void setDownloads(int downloads) {this.downloads = downloads;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Book that = (Book) o;if (downloads != that.downloads)return false;if (name != null ? !name.equals(that.name) :that.name != null) {return false;}return authorName != null ?authorName.equals(that.authorName) :that.authorName == null;}@Overridepublic int hashCode() {int result = name != null ? name.hashCode() : 0;result = 31 * result + (authorName != null ?authorName.hashCode() : 0);result = 31 * result + downloads;return result;}@Overridepublic String toString() {return "Book{" +"name='" + name + '\'' +", author='" + authorName + '\'' +", lastModifiedTimestamp='" + lastModifiedTimeStamp + '\'' +", rating='" + rating + '\'' +", downloads=" + downloads +'}';}
}

WOAH! That’s 96 lines of code for just storing 5 fields in an object. We aren’t doing much here besides having getter setters, toString(), equals() and hashCode() methods.

哇! 这是96行代码,仅在一个对象中存储5个字段。 除了拥有getter设置器, toString()equals()hashCode()方法之外,我们在这里没有做太多事情。

With the clean architectures and separation of code practices in our practices, we need to create POJO classes since every project needs to store data somewhere. This can increase the boilerplate code.

在我们的实践中采用干净的体系结构和代码实践的分离之后,我们需要创建POJO类,因为每个项目都需要将数据存储在某个地方。 这可以增加样板代码。

This is where Kotlin comes to the rescue, with the use of Data Classes.

这就是Kotlin使用数据类进行救援的地方。

Data Classes is Kotlin’s answer to reducing boilerplate code.

数据类是Kotlin对减少样板代码的答案。

The above POJO class can be written in Kotlin in the following way:

上面的POJO类可以通过以下方式用Kotlin编写:

data class Book(var name: String, var authorName: String, var lastModified: Long, var rating: Float, var downloads: Int)

THAT’S IT. Kotlin converts a 96 line java code to a single line of code.

而已。 Kotlin将96行的Java代码转换为单行代码。

This is Kotlin’s way of reducing the boilerplate code in your project!

这是Kotlin减少项目中样板代码的方式!

创建Kotlin数据类 (Creating Kotlin Data Class)

Following are the requirements for creating Kotlin Data class.

以下是创建Kotlin Data类的要求。

  • You need to append the class with the keyword data您需要在类中添加关键字data
  • The primary constructor needs to have at least one parameter.主构造函数需要至少具有一个参数。
  • Each parameter of the primary constructor must have a val or a var assigned.
    This isn’t the case with a normal class, where specifying a val or a var isn’t compulsory.主构造函数的每个参数都必须分配一个valvar
    普通类不是这种情况,在普通类中,不必指定valvar
  • Data classes cannot be appended with abstract, open, sealed or inner数据类不能附加abstractopensealedinner

Kotlin Data Class内置方法 (Kotlin Data Class built-in methods)

Kotlin Data class automatically creates the following functions for you.

Kotlin Data类自动为您创建以下功能。

  • equals() and hashCode()equals()hashCode()
  • toString() of the form "Book(name=JournalDev, authorName=Anupam)"toString()的形式为"Book(name=JournalDev, authorName=Anupam)"
  • componentN() functions for each of the parameters in the order specified. This is known as destructuring declarations.componentN()按指定的顺序对每个参数起作用。 这称为解构声明。
  • copy()copy()

Kotlin数据类功能 (Kotlin Data Class Features)

Following are some features that a Data Class provides.

以下是数据类提供的一些功能。

  • To create a parameterless constructor, specify default values to each of the parameters present in the primary constructor.要创建无参数构造函数,请为主要构造函数中存在的每个参数指定默认值。
  • A Data Class allows subclassing(No need to mention the keyword open).数据类允许子类化(无需提及关键字open )。
  • You can provide explicit implementations for the functions equals() hashCode() and toString()您可以为equals() hashCode()toString()函数提供显式实现
  • Explicit implementations for copy() and componentN() functions are not allowed.不允许对copy()componentN()函数进行显式实现。
  • We can control the visibility of the getters and setters by specifying the visibility modifiers in the constructor as shown below.
    data class Book(var name: String,private var authorName: String, var lastModified: Long, var rating: Float, var downloads: Int)

    我们可以通过在构造函数中指定可见性修饰符来控制getter和setter的可见性,如下所示。

  • A val parameter won’t have a setter defined implicitly(can’t be done explicitly too!).val参数不会隐式定义setter(也不能显式定义!)。

数据类中的默认参数和命名参数 (Default And Named Arguments in Data Class)

Following is our data class:

以下是我们的数据类:

data class Book(var name: String, var authorName: String, var lastModified: Long, var rating: Float, var downloads: Int)

None of the parameters have a default value set. So we need to set an argument for each of them in the instantiation as shown below.

这些参数均未设置默认值。 因此,我们需要在实例化中为每个参数设置一个参数,如下所示。

fun main(args: Array<String>) {
val book = Book("Android Tutorials","Anupam", 1234567, 4.5f, 1000)
}

Let’s set a few default arguments and see how the instantiation changes.

让我们设置一些默认参数,看看实例化如何变化。

data class Book(var name: String, var authorName: String = "Anupam", var lastModified: Long = 1234567, var rating: Float = 5f, var downloads: Int = 1000)
fun main(args: Array<String>) {
var book = Book("Android tutorials","Anupam", 1234567, 4.5f, 1000)book = Book("Kotlin")book = Book("Swift",downloads = 500)book = Book("Java","Pankaj",rating = 5f, downloads = 1000)book = Book("Python","Shubham",rating = 5f)}

Instead of setting each argument, we can set only the non-default ones and the ones which we wish too using the named argument.
Using Named Arguments, we can set the 5th argument as the second one by explicitly specifying the parameter name followed by =. Life is so easier this way!

除了设置每个参数,我们还可以使用named参数仅设置非默认参数和我们希望设置的参数
通过使用命名参数,我们可以通过显式指定参数名称后跟=来将第5个参数设置为第二个参数。 这样生活更轻松!

Kotlin数据类toString()方法 (Kotlin Data Class toString() Method)

The toString() is implicitly created and prints the argument names and labels for the instance as shown below.

toString()是隐式创建的,并打印实例的参数名称和标签,如下所示。

data class Book(var name: String, var authorName: String = "Anupam", var lastModified: Long = 1234567, var rating: Float = 5f, var downloads: Int = 1000)fun main(args: Array<String>) {var book = Book("Android tutorials","Anupam", 1234567, 4.5f, 1000)println(book)book = Book("Kotlin")println(book)book = Book("Swift",downloads = 500)println(book)book = Book("Java","Pankaj",rating = 5f, downloads = 1000)println(book.toString())book = Book("Python","Shubham",rating = 5f)println(book.toString())}//Following is printed in the console.
//Book(name=Android tutorials, authorName=Anupam, lastModified=1234567, rating=4.5, downloads=1000)
//Book(name=Kotlin, authorName=Anupam, lastModified=1234567, rating=5.0, downloads=1000)
//Book(name=Swift, authorName=Anupam, lastModified=1234567, rating=5.0, downloads=500)
//Book(name=Java, authorName=Pankaj, lastModified=1234567, rating=5.0, downloads=1000)
//Book(name=Python, authorName=Shubham, lastModified=1234567, rating=5.0, downloads=1000)

Note: print function implicitly adds a toString().

注意print函数隐式添加一个toString()。

Kotlin数据类copy()方法 (Kotlin Data Class copy() Method)

Copy function is used to create a copy of an instance of the data class with few of the properties modified.

复制功能用于创建数据类实例的副本,而很少修改属性。

It’s recommended to use val parameters in a data classes constructor in order to use immutable properties of an instances. Immutable objects are easier while working with multi-threaded applications.

建议在数据类构造函数中使用val参数,以使用实例的不可变属性。 使用多线程应用程序时,不可变对象更加容易。

Hence to create a copy of a immutable object by changing only few of the properties, copy() function is handy.

因此,通过仅更改少量属性来创建不可变对象的copy()copy()函数非常方便。

data class Book(val name: String, val authorName: String = "Anupam", val lastModified: Long = 1234567, val rating: Float = 5f, val downloads: Int = 1000)fun main(args: Array<String>) {val book = Book("Android tutorials","Anupam", 1234567, 4.5f, 1000)println(book)val newBook = book.copy(name = "Kotlin")println(newBook)
}
//Following is printed in the console.
//Book(name=Android tutorials, authorName=Anupam, lastModified=1234567, rating=4.5, downloads=1000)
//Book(name=Kotlin, authorName=Anupam, lastModified=1234567, rating=4.5, downloads=1000)

Kotlin数据类equals()和hashCode() (Kotlin Data Class equals() and hashCode())

The hashCode() method returns hash code for the object. If two objects are equal, hashCode() produces the same integer result. Hence, equals() returns true if the hashCode() is equal, else it returns a false.

hashCode()方法返回对象的哈希码。 如果两个对象相等,则hashCode()会产生相同的整数结果。 因此,如果hashCode()相等,则equals()返回true,否则返回false。

data class Book(val name: String, val authorName: String = "Anupam", val lastModified: Long = 1234567, val rating: Float = 5f, val downloads: Int = 1000)fun main(args: Array<String>) {val book = Book("Android tutorials","Anupam", 1234567, 4.5f, 1000)println("Hashcode is ${book.hashCode()}")val newBook = book.copy(name = "Kotlin")println("Hashcode is ${newBook.hashCode()}")val copyBook = book.copy()println("Hashcode is ${copyBook.hashCode()}")if(copyBook.equals(book))println("copyBook and book are equal")if(!book.equals(newBook))println("newBook and book are NOT equal")}//Following is printed in the console.
//Hashcode is 649213087
//Hashcode is 1237165820
//Hashcode is 649213087
//copyBook and book are equal
//newBook and book are NOT equal

The first and third object hashcodes are equal hence they are equal.

第一和第三对象哈希码相等,因此它们相等。

Note: The equals() method is equivalent to == in kotlin.

注意equals()方法等效于kotlin中的==

销毁声明 (Destructuring Declarations)

componentN() function lets us access each of the arguments specified in the constructor, in the order specified. N is the number of parameters in the constructor.

componentN()函数使我们可以按指定的顺序访问构造函数中指定的每个参数。 N是构造函数中的参数数。

data class Book(val name: String, val authorName: String = "Anupam", val lastModified: Long = 1234567, val rating: Float = 5f, val downloads: Int = 1000)fun main(args: Array<String>) {val book = Book("Android tutorials","Anupam", 1234567, 4.5f, 1000)println(book.component1()) //Android tutorialsprintln(book.component2()) //Anupamprintln(book.component3()) //1234567println(book.component4()) //4.5println(book.component5()) //1000}

Destructuring declarations allows us to access the arguments as properties from the class object as shown below.

解构声明使我们可以从类对象访问参数作为属性,如下所示。

data class Book(val name: String, val authorName: String = "Anupam", val lastModified: Long = 1234567, val rating: Float = 5f, val downloads: Int = 1000)fun main(args: Array<String>) {val book = Book("Android tutorials","Anupam", 1234567, 4.5f, 1000)val (n,a,date,rating,downloads) = book
}

Note: If a visibility modifier such as private is set on any of the arguments, it can’t be accessed in the above function.

注意 :如果在任何参数上设置了可见性修饰符(例如private),则无法在上述函数中访问它。

data class Book(val name: String,private val authorName: String = "Anupam", val lastModified: Long = 1234567, val rating: Float = 5f, val downloads: Int = 1000)fun main(args: Array<String>) {val book = Book("Android tutorials","Anupam", 1234567, 4.5f, 1000)val (n,a,date,rating,downloads) = book //This won't compile since authorName is private
}

That’s all for quick roundup on Kotlin Data Classes.

这就是快速汇总Kotlin数据类的全部内容。

References: Kotlin Docs

参考: Kotlin Docs

翻译自: https://www.journaldev.com/18594/kotlin-data-class

kotlin数据类

kotlin数据类_Kotlin数据类相关推荐

  1. kotlin sealed 中_Kotlin 数据类与密封类

    我的理解密封类就是一种专门用来配合 when 语句使用的类,举个例子,假如在 Android 中我们有一个 view,我们现在想通过 when 语句设置针对 view 进行两种操作:显示和隐藏,那么就 ...

  2. 转向Kotlin——数据类和封闭类

    数据类和封闭类是Kotlin中的两种特殊的类,今天一起了解一下.更多精彩内容也可以关注我的微信公众号--Android机动车 数据类 数据类是Kotlin的一个语法糖.Kotlin编译器会自动为数据类 ...

  3. Kotlin学习笔记 第二章 类与对象 第七节 数据类

    参考链接 Kotlin官方文档 https://kotlinlang.org/docs/home.html 中文网站 https://www.kotlincn.net/docs/reference/p ...

  4. Kotlin学习笔记12——数据类和密封类

    Kotlin学习笔记12--数据类和密封类 前言 数据类 在类体中声明的属性 复制 componentN 解构声明 密封类 尾巴 前言 上一篇,我们学习了Kotlin中的拓展,今天继续来学习Kotli ...

  5. 快速上手 Kotlin 开发系列之数据类和枚举

    本节讨论 Kotlin 的数据类.枚举类和密闭类. 数据类 数据类是 Kotlin 中很特殊的一种类,它可以将我们类中的成员变量自动的生成 getter/setter 方法,以及我们经常需要重写的 t ...

  6. Kotlin 学习笔记(二)—— 数据类、密闭类、循环写法以及常用集合操作符

    在上篇笔记中,我们对 Kotlin 的基本类型.关键字.类与对象,以及与 Java 之间互调的内容有了一些认识,这篇笔记来看看 Kotlin 中几种特殊的类,以及集合相关的常用操作. 1. Kotli ...

  7. Kt学习笔记(九)数据类、封闭类

    文章目录 一.数据类 1.1.使用数据类 1.2.对象复制 1.3.数据类成员的解构 二.封闭类 一.数据类   数据类是 Kotlin 的一个语法糖. Kotlin 编译器会自动为数据类生成一些成员 ...

  8. pandas获取dataframe数据列的数据类型、获取dataframe每类数据类型数据列的个数、使用select_dtypes函数、include参数以及exclude参数按照数据类型筛选数据

    pandas获取dataframe数据列的数据类型.获取dataframe每类数据类型数据列的个数.使用select_dtypes函数.include参数以及exclude参数按照数据类型筛选数据 目 ...

  9. php json对象取数据类型,PHP如何科学地json_encode类对象数据

    其实这篇文章更应该针对python, 因为python默认情况下json序列化一个类对象时,是要报错的. 但是我觉得php的码农更多吧,而且主要是想传达一种思想,思想无国界哈. 那就拿PHP举粟,我们 ...

最新文章

  1. POJ 3174 暴力枚举
  2. NOIP2017 小凯的疑惑
  3. 自动删除指定文件夹下N天前文件的批处理
  4. JavaScriptjQuery.stopPropogation()
  5. 一个div 上下两行_纯CSS实现单一div的正多边形变换
  6. P6619-[省选联考2020A/B卷]冰火战士【树状数组二分】
  7. php webp decode.h,HCTF两道web题目
  8. SQLConnect
  9. [转载] 消除vscode安装pylint后提示的unused variable
  10. 统计学中sp_统计学中pssp是什么意思
  11. 互联网公司面试流程面试技巧(附被无良HR欺骗的经历)
  12. 错误集--创建消息队列用户,用于controler和node节点连接rabbitmq的认证
  13. 一、Maven-单一架构案例(创建工程,引入依赖,搭建环境:持久化层,)
  14. Winsock API编程之UDP小结
  15. Rails——migration
  16. 吉他入门乐理知识精髓篇
  17. css大图切割,利用CSS切割图片技术来动态显示图片
  18. Excel表格中,删除列或行的快捷键是什么
  19. 树莓派Android Things物联网开发:GitHub案例程序汇总
  20. 内网渗透(十二)之内网信息收集-内网端口扫描和发现

热门文章

  1. [转]使用ThinkPHP框架快速开发网站(多图)
  2. windows 7 下 .net 开发环境的搭建
  3. [转载] C++ STL之 vector的capacity和size属性区别
  4. [转载] Python版简易计算器的实现
  5. 版本向量 使用css时正确区分IE版本[转]
  6. redis expire超时操作
  7. 2018-2019-1 20189208《Linux内核原理与分析》第九周作业
  8. BZOJ4557 JLOI2016侦察守卫(树形dp)
  9. Ubuntu14.04环境下配置TFTP服务器
  10. AsyncTask使用须知