数据类就是只存储数据,不包含操作行为的类
data class LoginUser(val username: String, val password: String)
//生成的类如下
public final class LoginUser {
@NotNull
private final String username;
@NotNull
private final String password;
@NotNull
public final String getUsername() {
return this.username;
}
@NotNull
public final String getPassword() {
return this.password;
}
public LoginUser(@NotNull String username, @NotNull String password) {//构造函数
Intrinsics.checkParameterIsNotNull(username, "username");
Intrinsics.checkParameterIsNotNull(password, "password");
super();
this.username = username;
this.password = password;
}
@NotNull
public final String component1() {//返回第一个值
return this.username;
}
@NotNull
public final String component2() {//返回第二个值
return this.password;
}
@NotNull
public final LoginUser copy(@NotNull String username, @NotNull String password) {
Intrinsics.checkParameterIsNotNull(username, "username");
Intrinsics.checkParameterIsNotNull(password, "password");
return new LoginUser(username, password);
}
// $FF: synthetic method
@NotNull
public static LoginUser copy$default(LoginUser var0, String var1, String var2, int var3, Object var4) {
if ((var3 & 1) != 0) {
var1 = var0.username;
}
if ((var3 & 2) != 0) {
var2 = var0.password;
}
return var0.copy(var1, var2);
}
@NotNull
public String toString() {
return "LoginUser(username=" + this.username + ", password=" + this.password + ")";
}
public int hashCode() {
String var10000 = this.username;
int var1 = (var10000 != null ? var10000.hashCode() : 0) * 31;
String var10001 = this.password;
return var1 + (var10001 != null ? var10001.hashCode() : 0);
}
public boolean equals(@Nullable Object var1) {
if (this != var1) {
if (var1 instanceof LoginUser) {
LoginUser var2 = (LoginUser)var1;
if (Intrinsics.areEqual(this.username, var2.username) && Intrinsics.areEqual(this.password, var2.password)) {
return true;
}
}
return false;
} else {
return true;
}
}
}
数据类自动创建的函数
编译器会根据主构造函数中声明的属性,自动创建以下3个函数。
- equals()/hashCode()函数toString()格式为"LoginUser(username="+this.username+",password="+this.password+")";
- component1()和component2()函数返回对应下标的属性值,按声明顺序排列;
- copy()函数:根据旧对象属性重新newLoginUser(username,password)一个对象出来。
如果这些函数在类中已经被明确定义了,或者从超类中继承而来,编译器就不再生成。
数据类的语法限制
- 主构造函数至少包含一个参数;
- 参数必须标识为val或者var;
- 不能为abstract、open、sealed或者inner;
- 不能继承其他类(但可以实现接口)。
数据类可以在解构声明中使用:
val loginUser = LoginUser("admin","admin")
val (username,password) = loginUser//解构声明
print("$username,$password")
Pair和Triple
二元组和三元组
data class Pair<out A, out B>(val first: A, val second: B) : Serializable {
override fun toString(): String = "($first,$second)"
}
public infix fun <A,B> A.to(that:B) :Pair<A,B> = Pair(this,that)//中缀函数 to
网友评论