user3338275
user3338275

Reputation: 240

Kotlin: secondary constructor with this keyword

data class DisjointSetNode<T>(var parent: DisjointSetNode<T>, var data: T, var rank: Int) {
constructor(data: T): this(parent = this, data = data, rank = 0)

I was wondering why I am getting an error saying that I cannot use the this keyword in the constructor call because I have not called the superclass constructor first. There is no superclass, and I want to make itself a parent. Any ideas of how I would go about doing this?

Upvotes: 2

Views: 1656

Answers (2)

holi-java
holi-java

Reputation: 30676

the problem is that you can't calling this during calling another constructor by this(...). you can take a look at JLS:

It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.

  • directly means calling this in this(...) at the first statement, e.g: this(this);.

  • indirectly means calling its members during call this(...), e.g:this(parent).

but you can makes the primary constructor to a secondary constructor to achieve your way, for example:

data class DisjointSetNode<T>(var data: T, var rank: Int = 0) {
    var parent: DisjointSetNode<T> = this

    constructor(parent: DisjointSetNode<T>, data: T) : this(data = data){
        this.parent = parent
    }
}

Upvotes: 1

mfulton26
mfulton26

Reputation: 31214

You cannot reference this in this context because it is not yet defined.

You can however move parent to outside the constructor signature. e.g.:

data class DisjointSetNode<T>(var data: T, var rank: Int = 0) {
    var parent: DisjointSetNode<T> = this
}

Upvotes: 1

Related Questions