Linus Klöckner
Linus Klöckner

Reputation: 11

How to pass class member to super classes constructor?

Why is it not possible to pass a member object to the super classes constructor?

This is working:


class Foo(private val whatever : Object = Object()) : BaseClass(whatever) {

    fun someFunction() {
        // Do something with "whatever"
        println(whatever.toString())
    }

}

But this isn't:


class Foo() : BaseClass(whatever) {

    private val whatever = Object()

    fun someFunction() {
        // Do something with "whatever"
        println(whatever.toString())
    }

}

The member whatever cannot be passed to the base class in the second example. That makes sense because the subclass is initialized after the baseclass and at this time whatever does not exist yet. But why is the first example working?

Upvotes: 1

Views: 1032

Answers (2)

Januson
Januson

Reputation: 4841

The problem is the Initialization Order.

First example works, because the argument of BaseClass's constructor is an argument of Foo's constructor. There is no problem. Argument is just passed.

Second example is not working because BaseClass's constructor needs to be invoked as a first step before the Foo's whatever property is initialized.

EDIT :

If you really need to initialize whatever inside of Foo, then you can use Companion Object.

class Foo2() : BaseClass(whatever) {

    companion object {
        private val whatever = Object()
    }

}

Upvotes: 1

Hayi Nukman
Hayi Nukman

Reputation: 1201

when creating a subclass of another class you call the constructor of these class, for example BaseClass(whatever). in this case, the whatever object is need to be created/passed as parameters in the primary constructor of these subclass.

In kotlin aside from creating the properties inside the class, also you can define it as parameters in the primary constructor using var/val. like class Foo(val whatever : Object)

but, its only on the primary constructor.

Upvotes: 0

Related Questions