Home > front end >  [Kotlin][Best Practice] How to pass receiver object in parameter function's parameter in Kotlin
[Kotlin][Best Practice] How to pass receiver object in parameter function's parameter in Kotlin

Time:12-15

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.

CodePudding user response:

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

CodePudding user response:

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)
    }
}
  • Related