I supposed this is a Kotlin general question, but ...
# android
t
I supposed this is a Kotlin general question, but I just use it for Android so... Coming from Python and other environments, I've tended to prefer explicit this/self for variable/method reference. We had an interesting bug today. Here's a method:
Copy code
fun drop() {
   Plan.modifyRegistry { registry ->
      registry.filterKeys { oid -> oid != this.oid }
   }
   MCCommand.planDrop.oid(oid).sendToMC()
}
Plan objects have an
oid
instance variable, and store themselves in a mini companion singleton. I'm sure there are all kinds of counter suggestions for this architecture. I'm hoping we can leave those aside. Recently, I decided to when-in-rome... and try to embrace implicit this. I let someone go through and "clean up" all of the redundant this's. And so this code got changed:
Copy code
fun drop() {
   Plan.modifyRegistry { registry ->
      registry.filterKeys { oid -> oid != oid }
   }
   MCCommand.planDrop.oid(oid).sendToMC()
}
And suddenly the
drop
method went from removing itself, to cleaning the whole registry. I'm not sure what the point is, but I guess I'm surprised that the way that Kotlin plays fast and furious with variable name bindings doesn't cause others more issues like this. It certainly makes it harder for me to want to let go of explicit this.
t
The problem is, not all of your
this
usage was redundant!
☝️ 1
Copy code
registry.filterKeys { oid -> oid != this.oid }
on the above line, the usage is not redundant
c
You ended up with
oid != oid
. They're the same variable. I can't imagine any language being able to automatically distinguish the two. So what happened is that an object is being checked against itself, and
oid != oid
will always be false. You actually do need
this
for this scenario, to make sure that the first
oid
refers to the lambda parameter, and the second refers to the class variable. Either that, or name the lambda parameter something different
t
I highly suggest only removing
this
when a tool tells you that you can. And even then, not being too trusting, making sure to test.
c
And yeah, like Tim said, it's too dangerous to remove all references to
this.
in an automated fashion. It's too easy for the scoping references to get swapped unintentionally when you move from an explicit to implicit receiver
💯 1