Calling a superclass class in Kotlin, Super is not an expression

I have two classes Entityand Accounthow

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

and

data class Account( 
    var name: String? = null,
    var accountFlags: Int? = null
) : Entity() {

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

What gives me an error

Super is not an expression; it can only be used on the left side of the dot. "

Why can't I do this?

The following is a compilation error, but I'm not sure if it is correct.

 constructor(entity: Entity) : this() {
    super.fromEntity(entity)
}
+28
source share
3 answers

You have a couple of problems in your code.

Firstly, this is the correct syntax to call the super constructor from the secondary constructor:

constructor(entity: Entity) : super(entity)

Secondly, you cannot call a super constructor from a constructor secondary if your class has a main constructor (which executes your class).

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

, . , .

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

, . a data class. , account.copy().

+61

super<Entity>.fromEntity(entity) .

:

Kotlin : , (, ), , , - , . .

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

0

- , .

class Account constructor(
        var name: String? = null,
        var accountFlags: Int? = null,
        id: String?,
        created: Date?
) : Entity(id, created) {

    companion object {
        fun fromEntity(entity: Entity): Account {
            return Account(null, null, entity.id, entity.created)
        }
    }
}
0

Source: https://habr.com/ru/post/1678976/


All Articles