创建数据类
data class Customer(val name: String, val email: String)
上述代码会创建一个Customer类,并包含以下功能:
- 所有属性的getter和setter
- equals()方法
- hashCode()方法
- toString()方法
- copy()方法
- component1() , component2() , …方法,分别对应定义的属性
反编译上述的class文件得到如下结果(并未把所有的方法内容列出):
public final class Customer {
@NotNull
private final String email;
@NotNull
private final String name;
@NotNull
public final String component1() {
return this.name;
}
@NotNull
public final String component2() {
return this.email;
}
@NotNull
public final Customer copy(@NotNull String name, @NotNull String email) {
Intrinsics.checkParameterIsNotNull(name, "name");
Intrinsics.checkParameterIsNotNull(email, "email");
return new Customer(name, email);
}
public boolean equals(java.lang.Object r3) {
......
}
public int hashCode() {
int i = 0;
String str = this.name;
int hashCode = (str != null ? str.hashCode() : 0) * 31;
String str2 = this.email;
if (str2 != null) {
i = str2.hashCode();
}
return hashCode + i;
}
public String toString() {
return "Customer(name=" + this.name + ", email=" + this.email + ")";
}
public Customer(@NotNull String name, @NotNull String email) {
Intrinsics.checkParameterIsNotNull(name, "name");
Intrinsics.checkParameterIsNotNull(email, "email");
this.name = name;
this.email = email;
}
@NotNull
public final String getEmail() {
return this.email;
}
@NotNull
public final String getName() {
return this.name;
}
}