我有一个 Kotlin 数据类:
data class PaymentAccount(
val accountId: Int,
val accountNumber: String,
val title: String
)
这就是我在 Java 中所做的:
创建一个抽象类:
public abstract class PaymentAccount {
protected int accountId;
protected String accountNumber;
protected String title;
public PaymentAccount(int accountId,
String accountNumber,
String title) {
this.accountId = accountId;
this.accountNumber = accountNumber;
this.title = title;
}
}
创建空对象并扩展抽象类:
public class NullPaymentAccount extends PaymentAccount {
public NullPaymentAccount() {
super(-1,
"Invalid account number",
"Invalid title");
}
}
创建一个真实的对象并扩展抽象类:
public class RealPaymentAccount extends PaymentAccount {
public RealPaymentAccount(int accountId,
String accountNumber,
String title) {
super(accountId,
accountNumber,
title);
}
}
如何在 Kotlin 中正确实现空对象模式?有不止一种方法吗?如果是这样,最简洁优雅的方式是什么?