Confusing apply scope function for object configuration

apply scope function injects this for inner properties to refer to the object being invoked. However adding this. to refer to every property being applied is redundant and is what make code dirty. Since apply allows us to ignore this. and refer to the properties directly it introduces shadow issue where property of outer scope will be referred.

So scope should have been designed without the this reference so that when used for object configuration would look clean and would remove the showing issue. adding this. is also confusing as in java it refers to the entire object enclosed.

var name = β€œv”
var person = Person().apply{
this.name = β€œj” - adding this. is redundant and looks bad when there are many properties.
name = β€œm” - we can omit this but now it references the outer name
}

But changing this is the whole point of apply()! If you don’t want that, why are you calling it at all? (If you need a block, also() or let() are available.)

1 Like

Agree. But as I pointed this is a keyword which already means what is same as in Java. So first putting prefix this. for every property is redundant and second when user reads this. he now has to check to which context does it point, whether it is the scope or the general object this. Your suggestion of using also and let are what makes this more pain. also aks us to use it which is same as using this. prefix and let required so reference to be prefixed. This is what make all the scope function jack of all trades and master of none.

 var name = "a"
 Person(name = "b").apply{
    name // a
    this.name // b
}

Now name refers to the local variable and this.name refers to the name of Person.

Do you want a feature to change the place of the prefix:

 fun test(){
     var name = "a"
     Person(name = "b").apply{
        name // b
        this@test.name // a
    }
}