说实话,写了这么多年代码,未曾这么干过。。
数据类:
kotlin中提供一个data
关键字,data
修饰的类就是一个数据类,对标java的bean类:
data class Book(val id: Long, val name: String, val author: Person)
data class Person(val id: Long, val name: String, val age: Int)
与java的bean类相比,kotlin的data类不能被继承,并且属性要全部写到构造函数当中,没有无参的构造函数。确实简便了许多!
并且编译器会为data类生成了一些好用的方法:
val book = Book(0, “Kotlin in Action”, Person(1, “Dmitry”, 40))
//编译器生成的方法 copy component1
book.copy()
val id = book.component1()
val name = book.component2()
val author = book.component3()
其中copy()
和 component1()
等都是编译器自动生成的,component方法的意义是方便解构赋值的使用:
//解构赋值,对应的字段是通过component方法获取的
val (id, name, author) = book
关于解构:
//解构
val pair = “Hello” to “World”
val (hello, world) = pair
data不能被继承,那么为啥不能有子类呢?
可以先看一下kotlin为data类生成的对应的java类是什么样的,查看方式,doule shift键,然后Actions中输入kotlin Bytecode显示:
点击Decompile即可查看对应生成的java代码
以下是Book的数据类对应生成的java代码
public final class Book {
private final long id;
@NotNull
private final String name;
@NotNull
private final Person author;
public final long getId() {
return this.id;
}
@NotNull
public final String getName() {
return this.name;
}
@NotNull
public final Person getAuthor() {
return this.author;
}
public Book(long id, @NotNull String name, @NotNull Person author) {
Intrinsics.checkNotNullParameter(name, “name”);
Intrinsics.checkNotNullParameter(author, “author”);
super();
this.id = id;
this.name = name;
this.author = author;
}
public final long component1() {
return this.id;
}
@NotNull
public final String component2() {
return this.name;
}
@NotNull
public final Person component3() {
return this.author;
}
@NotNull
public final Book copy(long id, @NotNull String name, @NotNull Person author) {
Intr