1.前言:
官网介绍: https://kotlinlang.org/docs/reference/data-classes.html
会自动帮我们生成get,set方法,减少代码编写量,更轻量级别的实体类。
2.使用说明:
data class User(val name: String, val age: Int)
会自动生成一下方法:
- equals()/hashCode() pair;
- toString() of the form “User(name=John, age=42)”;
- componentN() functions corresponding to the properties in their order of declaration;
- copy() function (see below).
3.注意事项:
Data Class 是一个final类
1.构造函数中至少有一个参数
2.构造函数中的参数都需要声明var 或者val
3.data class不能是抽象的,可继承的,或者内部类,因为这是一个final类
4.不能够为componentN()和copy()显示实现 (componentN 会根据构造方法中的参数,自动生成component1-componentN 的方法,所以不需要显示实现,如果显示实现,会提示报错)
5.如果需要显示的声明一个无参的构造方法,需要给构造方法里面的参数设置默认值
4.简单使用
1.在Android Studio中可以导入插件 JsonToKotlinClass,可使用该插件自动将json数据转换为对应的Data Class对象。
安装说明:File –> Settings –> Plugins –> Browse Repositories –>Search JsonToKotlinClass
如果安装失败,直接下载jar安装,地址:https://github.com/wuseal/JsonToKotlinClass/releases/download/V1.7.3/JsonToKotlinClass.jar
使用alt+k (window系统,穷*买不起mac)
出现如下界面,则可以创建自己的data class了。
2.Copying方法的使用
这里的user2 是从user对象copy过来的,使用了===作比较,该对象的引用发生改变。
这里使用了==比较2个User对象,发现返回的值为true,两个等号的时候比较的是非引用值,而是对应字段的内容是否相同。
3.解构声明(https://kotlinlang.org/docs/reference/multi-declarations.html )
类似下面的模样:
val (name, age) = person
for ((a, b) in collection) { ... }
for ((key, value) in map) {
// do something with the key and the value
}