Kotlin 中调用超类构造函数,Super 不是表达式 [英] Call super class constructor in Kotlin, Super is not an expression
问题描述
我有两个类 Entity
和 Account
作为
I have two classes Entity
and Account
as
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 '.'
为什么我不能这样做?
以下将通过编译错误,但我不确定是否正确.
The following will pass the compilation error, but I am not sure if it is correct.
constructor(entity: Entity) : this() {
super.fromEntity(entity)
}
推荐答案
你的代码有几个问题.
首先,这是从二级构造函数调用超级构造函数的正确语法:
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屋!