I have two classes EntityAccount 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)
    }
}

Which gives me the error

Super is not an expression, it can be only used in the left-h和 side of a dot '.'

Why cannot I do that?

以下代码将传递编译错误,但我不确定它是否正确.

 constructor(entity: Entity) : this() {
    super.fromEntity(entity)
}

推荐答案

代码中有几个问题.

首先,这是从二级构造函数调用超级构造函数的正确语法:

constructor(entity: Entity) : super(entity)

其次,如果你的类有primary constructor(你的类有primary constructor),你不能从secondary构造函数调用超级构造函数.

Solution 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)
}

这里,复制构造函数位于子类中,该子类只委托给主构造函数.

解决方案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
    }
}

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.

解决方案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协程挂起继续线程

在Mapstruct中重用@映射定义

在Kotlin中求n个ClosedRange实例相交的最常用方法是什么?

Kotlin中一个接口的实现问题

Scala性状线性化等价于Kotlin

在Kotlin中的嵌套when语句中,else块是强制性的吗?

协程子作业(job)取消

Android Jetpack Compose:在空的 Compose 活动中找不到 OutlinedTextField (Material3)

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

为什么多线程不会使执行更快

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

类型不匹配:Required: Context, Found: Intent

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

kotlin 扩展属性的惰性初始化器中的这个引用

如何捕获传递给模拟函数的参数并返回它?

如何在kotlin语言中将字符转换为ascii值

Android 上的 Kotlin:将map到list

IllegalStateException:function = , count = 3, index = 3

如何在 Kotlin 中定义新的运算符?