Call super class constructor in Kotlin, Super is not an expression

后端 未结 4 1390
天涯浪人
天涯浪人 2020-12-13 03:59

I have two classes Entity and Account as

abstract class Entity(
    var id: String? = null,
    var created: Date? = Date()) {

          


        
4条回答
  •  北海茫月
    2020-12-13 04:22

    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).

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

    Here, the copy constructor is in the child class which just delegates to the primary constructor.

    Solution 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.

    Solution 3 (most idiomatic)

    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()
    

    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().

提交回复
热议问题