为何在MainActivity代码中使用this@MainActivity?
this@MainActivity is needed instead of plain this in your lambda Great question! Let's break down how this behaves in Kotlin, especially when working with lambdas inside class members, to clear up your confusion.
Let's start with your MainActivity code
In the textSwitcher.setFactory lambda, you're creating a TextView—which requires a Context as its constructor parameter. If you tried using plain this here, it wouldn't refer to your MainActivity instance, and here's why:
The lambda you pass to setFactory() is Kotlin's way of implementing the ViewFactory interface behind the scenes. Inside this lambda, the default this points to the anonymous ViewFactory instance that gets created, not your MainActivity. Since ViewFactory isn't a Context, using plain this would throw a compilation error (the TextView constructor expects a Context, not a ViewFactory).
By writing this@MainActivity, you're explicitly telling Kotlin to use the this reference from the outer MainActivity scope. Since MainActivity inherits from AppCompatActivity (which itself inherits from Context), this gives you the valid Context the TextView needs.
Comparing to your test code
Your test code works as expected because there's no nested scope overriding this:
class class1(c:class2){ init{ c.output() } } class class2{ init{ class1(this) // This refers to the class2 instance } fun output(){ println("Hello.") } } fun main(){ val x = class2() }
Here, this is used directly in the init block of class2. The init block is part of the class2 instance's immediate scope, so there's no ambiguity—this clearly refers to the current class2 object. There's no inner lambda or interface implementation here to change what this points to.
Quick rules for this in Kotlin
- Plain
this: Always refers to the nearest enclosing scope. If you're inside a lambda that implements an interface, this points to that inner interface instance. - Labeled
this(likethis@MainActivity): Lets you "jump out" to an outer scope'sthisreference, which is super useful when you need to access the outer class instance from inside a lambda or inner class.
This is a super common pattern in Android development, especially when you need to access the activity's Context from inside UI component callbacks!
内容的提问来源于stack exchange,提问作者shn

