Sharan
Sharan

Reputation: 1275

How to use Kotlin's invoke operator to get a receiver on object instantiation

class Family() {
    fun addMember(name: String) {}

    inline operator fun invoke(body: Family.() -> Unit) {
        body()
    }
}

After using invoke operator function I can do something like this:

val family = Family().invoke { this:
    addMember("Android")
}

I have seen code structures where the declaration is simply by doing this.

val family = Family { this:
        addMember("Android")
    }

Upvotes: 0

Views: 1535

Answers (1)

Animesh Sahu
Animesh Sahu

Reputation: 8096

In current situation invoke can be called on a instance i.e.

val family = Family()

family {
    addMember(...)
}

If I understood correctly you want to create a new instance of Family and apply the block into the object, you can do this by putting the function under a companion.

class Family {
    fun addMember(name: String) {}

    companion object {
        inline operator fun invoke(body: Family.() -> Unit): Family {
            return Family().apply(body)
        }
    }
}

Now:

val family = Family {
    addMember(...)
}

Upvotes: 4

Related Questions