在Kotlin中调用超级类构造函数,Super不是表达式 [英] Call super class constructor in Kotlin, Super is not an expression
问题描述
我有两个类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不是一个表达式,它只能在表达式的左侧使用 点."
Super is not an expression, it can be only used in the left-hand side of a dot '.'
为什么我不能这样做?
Why cannot I do that?
以下内容将通过编译错误,但是我不确定它是否正确.
The following will pass the compilation error, but I am not sure if it is correct.
constructor(entity: Entity) : this() {
super.fromEntity(entity)
}
推荐答案
您的代码中有几个问题.
You have a couple of problems in your code.
首先,这是正确的语法,可以从辅助构造函数中调用超级构造函数:
First, this is the correct syntax, to call a super constructor from a secondary constructor:
constructor(entity: Entity) : super(entity)
第二,如果您的类具有主要构造函数(您的类确实如此),则不能从次要构造函数调用超级构造函数.
Second, you can't call a super constructor from a secondary constructor if your class has a primary constructor (which your class does).
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)
}
在这里,复制构造函数位于子类中,该子类仅委托给主要构造函数.
Here, the copy constructor is in the child class which just delegates to the primary constructor.
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
}
}
在这里,我仅在子类中使用辅助构造函数,这使我可以将它们委托给各个超级构造函数.请注意代码的长度.
Here I'm only using secondary constructors in the child class which lets me delegate them to individual super constructors. Notice how the code is pretty long.
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()
.
Here I omitted the copy constructors and made the properties abstract so the child class has all the properties. I also made the child class a data class
. If you need to clone the class, you can simply call account.copy()
.
这篇关于在Kotlin中调用超级类构造函数,Super不是表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!