I would like to access the scope of the calling class when creating an "anonymous inner class" in Kotlin. What would be the equivalent of Java's OuterScope.this syntax? example :

open class SomeClass {
    open fun doSomething() {
        // ...
    }
}

class MyClass {
    fun someFunc() {
        object : SomeClass() {
            override fun doSomething() {
                super<SomeClass>.doSomething()
                // Access the outer class context, in Java
                // this would be MyClass.this
            }
        }
    }
}

推荐答案

this@MyClass

JFYI:

fun MyClass.foo() {
    // in some nested thing:
    this@foo
    //...
}

Kotlin Reference: This expressions

Kotlin相关问答推荐

如何为集成测试配置Gradle JVM测试套件?

如果启用了Flyway迁移,则不能具有配置属性';datources.default.架构-生成

在Kotlin中的嵌套when语句中,else块是强制性的吗?

有没有办法在 jetpack compose 中将 TextField 密码点图标增加得更大?

Kotlin中反射中Int到可空Double的隐式转换失败

可组合项在返回后返回时组合导航句柄

从 Kotlin 调用 Java 时可以为空的规则是什么

如何将字符串格式化为电话号码kotlin算法

parallelStream()和asSequence().asStream().parallel()之间的区别

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

如何使用 Hilt 注入应用程序:ViewModel 中的上下文?

为什么 Kotlin 扩展运算符在传递原始可变参数时需要 toTypedArray()?

有没有办法重用 Job 实例?

.indices 在 kotlin 中的含义是什么?

Kotlin 无法找到或加载主类

@InlineOnly 注释是什么意思?

如何从定义它们的类外部调用扩展方法?

从代码块执行和返回(在 Elvis 运算符之后)

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有