this 和 this@ 的区别
明确作用域,调用的是哪个 class 的实例
1. 基本概念
this:指向当前作用域的接收者对象this@:带标签的this引用,用于明确指定特定作用域的接收者
2. 使用场景差异
普通 this
- 在扩展函数或带有接收者的 Lambda 表达式中,
this指向该接收者对象 - 在类的成员函数中,
this指向当前类实例
带标签的 this@ClassName
- 当存在嵌套的作用域时,用于明确引用外部类的实例
- 特别是在内部类、Lambda 表达式或匿名对象中访问外部类实例时使用
3. 在代码中的应用
// 在内部类或 Lambda 中访问外部类实例
private fun addEventListeners() {
val listener: FileEditorManagerListener = object : FileEditorManagerListener {
override fun fileOpened(@NotNull source: FileEditorManager, @NotNull file: VirtualFile) {
// 明确调用外部 SharedChatPane 类的方法
this@SharedChatPane.sendActiveFileInfo()
// this 指向 FileEditorManagerListener 类的对象实例
this.xxx();
}
// ...
}
}
4. 何时必须使用 this@
- 当内部作用域(如 Lambda、匿名类)也有自己的
this时 - 需要区分访问外部类实例还是内部作用域的
this - 避免命名冲突和歧义
简单来说,this@SharedChatPane 明确表示要访问的是 [SharedChatPane] 类的实例,而不是当前上下文中的其他对象。