Home > database >  How to use `apply` in Kotlin when property and function have the same variable name
How to use `apply` in Kotlin when property and function have the same variable name

Time:07-13

data class Foo(
  val aaa: String,
  val bbb: String
)
fun bar(aaa: String) {
  Foo().apply {
    aaa = aaa // this line gives error
    bbb = "bbb"
  }
}

IDE gives an error Val cannot be reassigned which suggests it's trying to reassign the function level aaa.

how can I correctly use apply here to assign value of function level variable aaa to Foo's property aaa?

CodePudding user response:

Use this reference

fun bar(aaa: String) {
    Foo().apply {
        this.aaa = aaa    // no error
        bbb = "bbb"       // this.bbb can also be used, but is excessive here
    }
}

CodePudding user response:

Like @Nikolai Shevchenko answered this can be done using this.

When having a szenario where this references multiple instances with a same variable name, you can add a label to determine the exact target.

fun bar(aaa: String) {
    Foo().apply {
        [email protected] = aaa    // no error
        bbb = "bbb"       // this.bbb can also be used, but is excessive here
    }
}
data class Foo1(var aaa: String, var bbb: String)
data class Foo2(var aaa: String)

fun bar(aaa: String) {
    Foo1().apply foo1@{
        Foo2().apply foo2@{
            // this.aaa references either Foo1 or Foo2, should have a label to target the correct one. When no label is given Foo2 will get the variable assignment
            [email protected] = aaa    // no error
            [email protected] = aaa    // no error
            bbb = "bbb"       // this.bbb can also be used, but is excessive here
        }
    }
}
  • Related