Aduait Pokhriyal
Aduait Pokhriyal

Reputation: 1559

[Kotlin][Best Practice] How to pass receiver object in parameter function's parameter in Kotlin

I have below code:

internal data class DataClass(
    val name: String
)

internal fun DataClass.defineService() {
    //Some code
    val config = this
    return SomeOtherClassB.someAPI() { () -> 
        createService(config)
    }
}

internal fun SomeOtherClassA.createService(
    config: DataClass
){
    //Some code
}

What's the best way to pass DataClass from defineService() to createService()? I don't want to assign val config = this, doesn't feel right.

Upvotes: 0

Views: 259

Answers (2)

dominicoder
dominicoder

Reputation: 10165

What's the best way to pass DataClass from defineService() to createService()?

Use a qualified this statement:

internal fun DataClass.defineService() {
    //Some code
    return SomeOtherClassB.someAPI() { () -> 
        createService(this@defineService)
    }
}

Upvotes: 2

Tenfour04
Tenfour04

Reputation: 93639

You can skip the intermediate variable and put createService(this@defineService). This allows you to specify the this of the scope of defineService.

Upvotes: 2

Related Questions