我有两个类 Entity
和 Account
作为
abstract class Entity(
var id: String? = null,
var created: Date? = Date()) {
constructor(entity: Entity?) : this() {
fromEntity(entity)
}
fun fromEntity(entity: Entity?): Entity {
id = entity?.id
created = entity?.created
return this;
}
}
和
data class Account(
var name: String? = null,
var accountFlags: Int? = null
) : Entity() {
constructor(entity: Entity) : this() {
super(entity)
}
}
这给了我错误
Super is not an expression, it can be only used in the left-hand side of a dot '.'
为什么我不能这样做?
下面会通过编译错误,但不知道是否正确。
constructor(entity: Entity) : this() {
super.fromEntity(entity)
}
最佳答案
您的代码中有几个问题。
首先,这是从二级构造函数调用 super 构造函数的正确语法:
constructor(entity: Entity) : super(entity)
其次,如果你的类有一个主构造函数(你的类有),你就不能从一个辅助构造函数调用一个 super 构造函数。
解决方案 1
abstract class Entity(
var id: String,
var created: Date
)
class Account(
var name: String,
var accountFlags: Int,
id: String,
created: Date
) : Entity(id, created) {
constructor(account: Account) : this(account.name, account.accountFlags, account.id, account.created)
}
这里,复制构造函数在子类中,它只是委托(delegate)给主构造函数。
解决方案 2
abstract class Entity(
var id: String,
var created: Date
) {
constructor(entity: Entity) : this(entity.id, entity.created)
}
class Account : Entity {
var name: String
var accountFlags: Int
constructor(name: String, accountFlags: Int, id: String, created: Date) : super(id, created) {
this.name = name
this.accountFlags = accountFlags
}
constructor(account: Account) : super(account) {
this.name = account.name
this.accountFlags = account.accountFlags
}
}
这里我只在子类中使用辅助构造函数,这让我可以将它们委托(delegate)给单独的 super 构造函数。注意代码很长。
解决方案 3(最惯用的)
abstract class Entity {
abstract var id: String
abstract var created: Date
}
data class Account(
var name: String,
var accountFlags: Int,
override var id: String,
override var created: Date
) : Entity()
这里我省略了复制构造函数并将属性抽象化,因此子类具有所有属性。我还将子类设为data class
。如果需要克隆类,只需调用 account.copy()
。
关于kotlin - Kotlin中调用父类(super class)构造函数,Super不是表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481268/