
kotlin data class 解析

官方文档
Data classes in Kotlin are primarily used to hold data. For each data class, the compiler automatically generates additional member functions that allow you to print an instance to readable output, compare instances, copy instances, and more. Data classes are marked with data:
Kotlin 中的数据类主要用于保存数据。对于每个数据类,编译器都会自动生成额外的成员函数,允许你将实例打印到可读的输出、比较实例、复制实例等等。数据类以
data
标记:
1 data class User(val name: String, val age: Int)The compiler automatically derives the following members from all properties declared in the primary constructor:
编译器自动从主构造函数中声明的所有属性派生以下成员:
equals()
/hashCode()
pair.equals()
/hashCode()
对。toString()
of the form “User(name=John, age=42)
“.
形式为 “User(name=John, age=42)
“ 的toString()
。componentN()
functions corresponding to the properties in their order of declaration.componentN()
函数按声明顺序对应于属性。copy()
function (see below).copy()
函数(见下文)。
对于这几个函数,值得说的有两个,一个是 componentN()
另一个是 copy()
我们直接用个例子来看:
1 | data class Person( |
我们反编译成 java 来看看
1 |
|
没想到,反编译出来居然这么长,但是并不复杂
可以看到,这里面没有默认构造函数(无参构造函数)
componentN
这个 componentN
居然只是返回了其中的一个对象
我们来看看如何使用这个函数:
1 | fun main() { |
此时我们反编译成 java
1 | public final class MainKt { |
可以看到他就是直接使用 componentN
来返回其中的类成员变量的
copy
copy()
方法,用于复制当前对象,并允许在复制的同时修改某些属性的值。这是实现不可变对象修改的神器!
代码如下:
1 | val p1 = Person("Tom", 23) |
为什么直接使用构造函数呢?
- 原因一:如果你有很多类成员变量,一一去初始化会很麻烦
- 原因二:增强可读性,这样写代码能看出来对象之间的关系,就比如上面代码就是
p2
的年龄比p1
长 1 岁
- Title: kotlin data class 解析
- Author: lucas
- Created at : 2025-04-25 15:34:06
- Updated at : 2025-04-26 23:49:26
- Link: https://darkflamemasterdev.github.io/2025/04/25/kotlin-data-class-解析/
- License: This work is licensed under CC BY-NC-SA 4.0.